Module: Truncates

Defined in:
lib/truncates.rb,
lib/truncates/version.rb

Constant Summary collapse

DEFAULT_MAX_LENGTH =
255
DEFAULT_CHARACTER_TRAIL =
""
DEFAULT_ON =
:validation
VERSION =
"0.0.8"

Instance Method Summary collapse

Instance Method Details

#truncates(field_name, options = {}) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/truncates.rb', line 8

def truncates(field_name, options = {})
  raise("Hash expected, got #{options.class.name}") if !options.is_a?(Hash) && !options.empty?
  max_length = options[:max_length] || DEFAULT_MAX_LENGTH
  character_trail = options[:character_trail] || DEFAULT_CHARACTER_TRAIL    
  on = options[:on] || DEFAULT_ON
    puts "field_name: #{field_name}\non: #{on}"
  case on.to_s
  when "validation"
    before_validation do
      value = eval("self.#{field_name}")      
      
      if(value.present? && value.length > max_length)
        new_value = value.slice(0, max_length - character_trail.length) + character_trail        
        eval("self.#{field_name}=\"#{new_value}\"")
      end
    end
  when "set"
    define_method "#{field_name}=" do |value|
      new_value = value
      if(value.present? && value.length > max_length)
        new_value = value.slice(0, max_length - character_trail.length) + character_trail
      end
      
      begin
        super(new_value)
      rescue NoMethodError
        eval("@#{field_name} = \"#{new_value}\"") 
      end
    end  
  end
end