Module: SimpleHstoreAccessor

Defined in:
lib/simple_hstore_accessor.rb,
lib/simple_hstore_accessor/version.rb

Constant Summary collapse

VERSION =
"0.0.2"

Instance Method Summary collapse

Instance Method Details

#store_accessor(hstore_attribute, *keys) ⇒ Object

Public: Rails4-like method which defines simple accessors for hstore fields

hstore_attribute - your Hstore column keys - Array of fields in your hstore

Example

class Person < ActiveRecord::Base
  store_accessor :favorites_info, :book, :color
end

Returns nothing



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/simple_hstore_accessor.rb', line 18

def store_accessor(hstore_attribute, *keys)
  Array(keys).flatten.each do |key|
    define_method("#{key}=") do |value|
      send("#{hstore_attribute}_will_change!")
      send("#{hstore_attribute}=", (send(hstore_attribute) || {}).merge(key.to_s => value))
    end
    define_method(key) do
      send(hstore_attribute) && send(hstore_attribute)[key.to_s]
    end
  end
end