Skip to content

Instantly share code, notes, and snippets.

@kirel
Created February 5, 2013 17:49
Show Gist options
  • Select an option

  • Save kirel/4716207 to your computer and use it in GitHub Desktop.

Select an option

Save kirel/4716207 to your computer and use it in GitHub Desktop.
# Reimplementation of ActiveRecord::Store to be compatible with Enumerize.
# Explanation:
# Enumerize defines it's accessors on some module that is then included into the class. This works well
# for i.e. AR because accessors are in the method search path before AR attributes.
# ActiveRecord::Store defines accessors directly on the class thus Enumerize accessors are shadowed.
# This implementation defines store accessors on another module instead. As long as this one is mixed in before
# the Enumerize module everything works as expected.
# That means `store` has to be called and set up before `enumerize`. Same goes for the corresponding includes/extends.
module EnumerizeCompatibleStore
extend ActiveSupport::Concern
module ClassMethods
def store(store_attribute, options = {})
include _enumerize_compatible_store_module
serialize store_attribute, Hash
store_accessor(store_attribute, options[:accessors]) if options.has_key? :accessors
end
def store_accessor(store_attribute, *keys)
Array(keys).flatten.each do |key|
_enumerize_compatible_store_module.module_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{key}=(value)
self.#{store_attribute}={} unless #{store_attribute}.is_a?(Hash)
#{store_attribute}[:#{key}] = value
#{store_attribute}_will_change!
end
def #{key}
self.#{store_attribute}={} unless #{store_attribute}.is_a?(Hash)
#{store_attribute}[:#{key}]
end
RUBY
end
end
def _enumerize_compatible_store_module
@_enumerize_compatible_store_module ||= Module.new
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment