public
Last active

hstore accessor class method for AR

  • Download Gist
hstore_accessor.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# include from an initializer
 
module HstoreAccessor
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def hstore_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
end
end
 
ActiveRecord::Base.send(:include, HstoreAccessor)

works great, thanks!

this is awesome, thanks!

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.