-
-
Save olivoil/2939584 to your computer and use it in GitHub Desktop.
hstore accessor class method for AR
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# put this file in lib/ and include it from an initializer | |
module HstoreAccessor | |
def self.included(base) | |
base.extend(ClassMethods) | |
end | |
module ClassMethods | |
def hstore_accessor(hstore_attribute, *keys) | |
serialize hstore_attribute, ActiveRecord::Coders::Hstore | |
Array(keys).flatten.each do |key| | |
define_method("#{key}=") do |value| | |
send("#{hstore_attribute}=", (send(hstore_attribute) || {}).merge(key.to_s => value)) | |
send("#{hstore_attribute}_will_change!") | |
end | |
define_method(key) do | |
send(hstore_attribute) && send(hstore_attribute)[key.to_s] | |
end | |
end | |
end | |
end | |
end | |
ActiveRecord::Base.send(:include, HstoreAccessor) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment