Module: ToHash

Defined in:
lib/to_hash.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.eval_attributes(object, attributes) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/to_hash.rb', line 10

def self.eval_attributes(object, attributes)
  result = {}
  attributes = attributes.first if attributes.first.kind_of?(Hash)
  case attributes
  when Array
    attributes.each do |attribute|
      if attribute.kind_of?(Array)
        result[attribute.first] = eval_object(object.send(attribute.first), attribute[1..-1])
      else
        result[attribute] = object.send(attribute)
      end
    end
  when Hash
    attributes.each do |key, attribute|
      if attribute.kind_of?(Array)
        result[key] = eval_object(object.send(attribute.first), attribute[1..-1])
      else
        result[key] = object.send(attribute)
      end
    end
  end
  result
end

.eval_object(object, attributes) ⇒ Object



2
3
4
5
6
7
8
# File 'lib/to_hash.rb', line 2

def self.eval_object(object, attributes)
  if object.kind_of?(Array)
    object.map { |o| eval_attributes(o, attributes) }
  else
    eval_attributes(object, attributes)
  end
end

Instance Method Details

#to_hash(*attributes) ⇒ Object



34
35
36
# File 'lib/to_hash.rb', line 34

def to_hash(*attributes)
  ToHash.eval_attributes(self, attributes)
end