Module: Representation::ActiveRecord::InstanceMethods

Defined in:
lib/representation/active_record.rb

Instance Method Summary collapse

Instance Method Details

#representation(name) ⇒ Object Also known as: as



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/representation/active_record.rb', line 29

def representation(name)
  attributes_and_method_names = self.class.values_for_representation(name)
  represented_attributes = attributes_and_method_names.inject({}) do |attributes, val|
    attributes.merge({val.to_s => send(val)})
  end

  clone.tap do |represented_object|
    represented_object.instance_variable_set('@attributes', represented_attributes)
  
    represented_attributes.each do |key, value|
      represented_object.singleton_class.send :attr_accessor, key.to_sym
      represented_object.send "#{key}=".to_sym, value
    end
  
    def represented_object.attributes
      @attributes
    end
  
    def represented_object.inspect
      attributes_as_nice_string = @attributes.keys.map {|name| "#{name}: #{attribute_for_inspect(name)}"}
      "#<#{self.class} #{attributes_as_nice_string.compact.join(", ")}>"
    end
  end
end