Skip to content

Instantly share code, notes, and snippets.

@virtualstaticvoid
Created January 30, 2014 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save virtualstaticvoid/8704489 to your computer and use it in GitHub Desktop.
Save virtualstaticvoid/8704489 to your computer and use it in GitHub Desktop.
Single Table Inheritance + Hstore = Lovely Combination (http://www.devmynd.com/blog/2013-3-single-table-inheritance-hstore-lovely-combination)
# config/initializers/hstore_accessor.rb
# http://www.devmynd.com/blog/2013-3-single-table-inheritance-hstore-lovely-combination
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}=", (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