Created
June 9, 2012 14:26
-
-
Save zlw/2901165 to your computer and use it in GitHub Desktop.
This file contains 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
module HstoreAccessor | |
extend ActiveSupport::Concern | |
module ClassMethods | |
# Define accessors method for HStore field | |
# | |
# @param [Symbol] hstore name of HStore field | |
# @param [Array] fields list of accessors methods to define | |
def hstore_accessor(hstore, *fields) | |
fields.each do |field| | |
define_hstore_reader hstore, field | |
define_hstore_writer hstore, field | |
end | |
end | |
private | |
def define_hstore_reader(hstore, field) | |
define_method field do | |
send(hstore) && send(hstore)[field] | |
end | |
end | |
def define_hstore_writer(hstore, field) | |
define_method :"#{field}=" do |val| | |
val = (send(hstore) || {}).merge(field => val) | |
send(:"#{hstore}=", val) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment