Skip to content

Instantly share code, notes, and snippets.

@slawosz
Last active December 17, 2015 00:59
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 slawosz/5525555 to your computer and use it in GitHub Desktop.
Save slawosz/5525555 to your computer and use it in GitHub Desktop.
hstore on rails
# all including models requires column named 'data' of type hstore
module Extensions
module AttributeField
extend ActiveSupport::Concern
included do
class_attribute :attributes
self.attributes = Hash.new {|k,v| k[v] = []}
end
module ClassMethods
# data columns keys always as strings!
def field(name)
self.attributes[self] << name
class_eval do
define_method name do
data[name.to_s] if data.present?
end
define_method "#{name}=" do |new_value|
self.data = {} if data.nil?
self.data[name.to_s] = new_value
end
end
end
def available_attributes
klasses = self.ancestors.select {|klass| klass <= Item}
klasses.inject([]) do |memo, klass|
memo += attributes[klass]
end
end
end
end
end
class Aircraft < AircraftType
include Extensions::AttributeField
# this will create fields that are stored in hstore column (named data) but accessible as normal AR columns
field :serial_number
field :registration
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment