Module: EntityStore::HashSerialization

Defined in:
lib/entity_store/hash_serialization.rb

Instance Method Summary collapse

Instance Method Details

#attribute_methodsObject



30
31
32
33
34
35
# File 'lib/entity_store/hash_serialization.rb', line 30

def attribute_methods
  public_methods
    .select { |m| m =~ /\w\=$/ }
    .collect { |m| m.to_s.chop.to_sym }
    .select { |m| respond_to?(m) }
end

#attribute_value(value) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/entity_store/hash_serialization.rb', line 37

def attribute_value(value)
  if value.respond_to?(:attributes)
    value.attributes
  elsif value.is_a?(Hash)
    h = {}
    value.each_pair do |k,v| h[k] = attribute_value(v) end
    h
  elsif value.is_a?(Array)
    value.collect { |v| attribute_value(v) }
  else
    value
  end
end

#attributesObject Also known as: to_hash, to_h

Public - generate attributes hash did use flatten but this came a-cropper when the attribute value was an array



19
20
21
22
23
24
25
# File 'lib/entity_store/hash_serialization.rb', line 19

def attributes
  attrs = {}
  attribute_methods
    .collect { |m| [m, attribute_value(send(m))] }
    .each do |item| attrs[item[0]] = item[1] end
  attrs
end

#initialize(attr = {}) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/entity_store/hash_serialization.rb', line 4

def initialize(attr={})
  values = attr
  values = values.attributes if values.respond_to? :attributes

  unless values.is_a? Hash
    raise "Do not know how to create #{self.class} from #{attr.class}"
  end

  values.each do |key, value|
    send("#{key}=", value) if respond_to?("#{key}=")
  end
end