Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
hstore accessor class method for AR
# 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)
@taboularasa

This comment has been minimized.

Copy link

taboularasa commented Feb 6, 2013

works great, thanks!

@Charlie-Y

This comment has been minimized.

Copy link

Charlie-Y commented Oct 21, 2013

this is awesome, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.