Skip to content

Instantly share code, notes, and snippets.

@luan
Created August 24, 2012 17:54
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 luan/3453477 to your computer and use it in GitHub Desktop.
Save luan/3453477 to your computer and use it in GitHub Desktop.
module HStored
module ClassMethods
def field(key, options = {})
key = key.to_s
scope "has_#{key}", lambda { |value| where("properties @> (? => ?)", key, value) }
define_method(key) do
return options[:default] if options[:default] && !(properties && properties[key])
property = properties && properties[key]
if options[:type] && options[:type] == Date
begin
property = property.to_date if property
rescue
property = nil
end
elsif options[:type] && options[:type] != String
property = eval(property.to_s) if property
end
property
end
define_method("#{key}_before_type_cast") do
return options[:default] if options[:default] && !(properties && properties[key])
property = properties && properties[key]
property
end
define_method("#{key}=") do |value|
self.properties = (properties || {}).merge(key => value)
end
end
end
module InstanceMethods
end
def self.included(receiver)
receiver.extend ClassMethods
receiver.send :include, InstanceMethods
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment