Skip to content

Instantly share code, notes, and snippets.

@kfatehi
Created April 29, 2012 21:22
Show Gist options
  • Save kfatehi/2553328 to your computer and use it in GitHub Desktop.
Save kfatehi/2553328 to your computer and use it in GitHub Desktop.
Hstore ActiveRecord::Base method_missing
## Hstore Method Missing Extension
module HstoreModel
def method_missing(method, *args, &block)
if !self.class.attribute_methods_generated?
self.class.define_attribute_methods
if respond_to_without_attributes?(method)
send(method, *args, &block)
else
super
end
elsif data[(key = method.to_s.gsub('=',''))]
if method[-1] == "="
# Hstore Setter
self.class.send :define_method, method do
binding.pry
data[key] = args
end
else
# Hstore Getter
self.class.send :define_method, method do
data[key]
end
end
self.send(method, *args, &block)
else
super
end
end
end
## Thing.rb
class Thing < ActiveRecord::Base
include HstoreModel
end
# I can now get/set Thing's hstore attributes ('data' is an hstore attribute on Thing) as though they were "native". Yay it works with Formtastic now
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment