Module: ActiveResourceExtensions::ResourceWithSchema::InstanceMethods

Defined in:
lib/active_resource_extensions/resource_with_schema.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/active_resource_extensions/resource_with_schema.rb', line 66

def method_missing name, *args, &block
  if self.class.is_attribute? name
    value = attributes[name.to_s]
    return if value.nil?
    case self.class.attribute_type name
    when 'Time'
      Time.parse value
    when 'Date'
      Date.parse value
    when 'Integer'
      value.to_i
    when 'Float'
      value.to_f
    when 'Boolean'
      [true, 1, '1'].include? value
    when 'ObjectId'
      value.to_s
    when ''
      value
    else
      begin
        self.class.attribute_type( name ).constantize.new value
      rescue ArgumentError, NameError
        raise ArgumentError, "Can't cast #{value.inspect} into #{self.class.attribute_type( name )}"
      end
    end
  else
    super name, *args, &block
  end
end

Instance Method Details

#load(attributes) ⇒ Object

Automatically add attributes that are referenced in the schema but are not passed as parameters.

Parameters:

  • attributes (Hash)

    Hash of record’s attributes.

Returns:

  • (Object)

    self.



57
58
59
60
61
62
63
# File 'lib/active_resource_extensions/resource_with_schema.rb', line 57

def load attributes
  super attributes
  for attribute_name in self.class.schema.keys
    @attributes[attribute_name.to_s] = nil unless @attributes.has_key?(attribute_name.to_s)
  end
  self
end

#update_attributes(attributes) ⇒ Boolean

Update attributes of record before saving the record

Parameters:

  • attributes (Hash)

    Hash of record’s attributes.

Returns:

  • (Boolean)

    Result of save.



43
44
45
46
47
48
49
# File 'lib/active_resource_extensions/resource_with_schema.rb', line 43

def update_attributes( attributes )
  attributes.each_pair do |attribute_name, value|
    raise ArgumentError, "#{attribute_name.inspect} is not declared in schema." unless self.class.is_attribute?( attribute_name )
    @attributes[attribute_name.to_s] = value
  end
  save
end