Module: Sequel::Plugins::JsonAttributes::ClassMethods

Defined in:
lib/sequel_json_attributes.rb

Instance Method Summary collapse

Instance Method Details

#store(attribute, options) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/sequel_json_attributes.rb', line 5

def store attribute, options
  options[:accessors].each do |accessor|
    #define reader
    send :define_method, accessor do
      json = send attribute
      if json
        JSON.parse(json)[accessor.to_s]
      else
        nil
      end
    end

    #define writer
    send :define_method, "#{accessor.to_s}=".to_sym do |value|
      json = send(attribute) || {}.to_json
      parsed_json = JSON.parse json
      parsed_json[accessor.to_s] = value
      send "#{attribute.to_s}=".to_sym, parsed_json.to_json
      value
    end
  end
end