Skip to content

Instantly share code, notes, and snippets.

@stakes
Created February 24, 2011 20:11
Show Gist options
  • Save stakes/842797 to your computer and use it in GitHub Desktop.
Save stakes/842797 to your computer and use it in GitHub Desktop.
Attribute Serializer with dynamic finders
module AttributeSerializer
module ActiveRecordExtensions
module ClassMethods
def serializeable(serialized, serialized_accessors={})
serialize serialized, serialized_accessors.class
serialized_attr_accessor serialized, serialized_accessors
default_serialized_attr serialized, serialized_accessors
serialized_finder serialized, serialized_accessors
end
# Creates the accessors
def serialized_attr_accessor(serialized, accessors)
accessors.keys.each do |k|
define_method("#{k}") do
self[serialized] && self[serialized][k]
end
define_method("#{k}=") do |value|
self[serialized][k] = value
end
end
end
# Sets the default value of the serialized field
def default_serialized_attr(serialized, accessors)
method_name = "set_default_#{serialized}"
after_initialize method_name
define_method(method_name) do
self[serialized] = accessors if self[serialized].nil?
end
end
# Creates finders
def serialized_finder(serialized, accessors)
accessors.keys.each do |k|
method_name = "find_by_#{k}"
define_singleton_method(method_name) do |val=nil|
a = []
self.all.each do |s|
a << s if s.options[k] == val
end
a unless a.empty?
end
end
end
end
end
end
class ActiveRecord::Base
extend AttributeSerializer::ActiveRecordExtensions::ClassMethods
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment