Module: ElasticAttributes

Defined in:
lib/elastic_attributes.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



106
107
108
109
110
111
112
# File 'lib/elastic_attributes.rb', line 106

def included(klass)
  klass.instance_eval do
    # cattr_accessible
    [:attributes, :default_attribute].each {|n|instance_eval"def #{n};@#{n};end; def #{n}=(v);@#{n}=v;end" }
  end
  klass.extend ElasticAttributes::ClassMethods
end

Instance Method Details

#decode(data) ⇒ Object

Unserialize data: map it to the current object attributes.



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/elastic_attributes.rb', line 31

def decode data
  if data.is_a? Hash
    self.class.attributes.each do |name, options|
      send("#{name}=", processed_data(data[name] || data[name.to_s], options))
    end
  elsif name = self.class.default_attribute
    options = self.class.attributes[name]
    send("#{name}=", processed_data(data, options))
  else
    raise ArgumentError.new("data is not a Hash (it\'s a #{data.class}) and default attribute not specified")
  end
end

#encodeObject

Serialize data



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/elastic_attributes.rb', line 45

def encode
  if (name = self.class.default_attribute) && ! (self.class.attributes.keys - [name]).any?{|n|send(n)}
    send(name)
  else
    Hash[(
      self.class.attributes.keys.map do |name|
        value = encoded_data(send(name), self.class.attributes[name])
        [name.to_s, value] if value
      end.compact
    )]
  end
end