Class: Virgola::Attribute

Inherits:
Object
  • Object
show all
Defined in:
lib/virgola/attribute.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, type = String, *args) ⇒ Attribute

Returns a new instance of Attribute.



11
12
13
14
15
16
# File 'lib/virgola/attribute.rb', line 11

def initialize(name,type=String,*args)
  @name    = name
  @type    = type
  @value   = nil
  @options = args.extract_options!
end

Instance Attribute Details

#nameObject

Returns the value of attribute name.



9
10
11
# File 'lib/virgola/attribute.rb', line 9

def name
  @name
end

#optionsObject

Returns the value of attribute options.



9
10
11
# File 'lib/virgola/attribute.rb', line 9

def options
  @options
end

#typeObject

Returns the value of attribute type.



9
10
11
# File 'lib/virgola/attribute.rb', line 9

def type
  @type
end

Instance Method Details

#==(attribute) ⇒ Object



51
52
53
54
# File 'lib/virgola/attribute.rb', line 51

def ==(attribute)
  return false unless attribute.is_a?(Attribute)
  self.name == attribute.name
end

#cast(value) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/virgola/attribute.rb', line 25

def cast(value)
  if    self.type == Float    then value.to_f
  elsif self.type == Time     then Time.parse(value)
  elsif self.type == Date     then Date.parse(value)
  elsif self.type == DateTime then DateTime.parse(value)
  elsif self.type == Boolean  then ['true', 't'].include?(value.to_s.downcase)
  elsif self.type == Integer  then
    # ganked from happymapper :)
    value_to_i = value.to_i
    if value_to_i == 0 && value != '0'
      value_to_s = value.to_s
      begin
        Integer(value_to_s =~ /^(\d+)/ ? $1 : value_to_s)
      rescue ArgumentError
        nil
      end
    else
      value_to_i
    end
  else
    value
  end
rescue
  value
end

#map(mapped_object, value) ⇒ Object



18
19
20
# File 'lib/virgola/attribute.rb', line 18

def map(mapped_object, value)
  mapped_object.send("#{self.name}=", cast(value))
end