Module: Jattrs::JsonAttributesClassMethods

Defined in:
lib/jattrs.rb

Instance Method Summary collapse

Instance Method Details

#jattr_accessor(field_name, *methods) ⇒ Object



11
12
13
14
# File 'lib/jattrs.rb', line 11

def jattr_accessor(field_name, *methods)
  jattr_reader(field_name, methods)
  jattr_writer(field_name, methods)
end

#jattr_reader(field_name, methods) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/jattrs.rb', line 16

def jattr_reader(field_name, methods)
  methods.each do |method|
    next if respond_to?(method)

    define_method("#{method}") do
      send(field_name)[method.to_s]
    end
  end
end

#jattr_writer(field_name, methods) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/jattrs.rb', line 26

def jattr_writer(field_name, methods)
  methods.each do |method|
    next if respond_to?(method)

    define_method("#{method}=") do |object_value|  
      if send(field_name).nil?
        self.send("#{field_name}=", { method.to_s => object_value })
      else
        send(field_name)[method.to_s] = object_value
      end
    end
  end
end