Skip to content

Instantly share code, notes, and snippets.

@ruby-fu-ninja
Created January 17, 2013 07:19
Show Gist options
  • Save ruby-fu-ninja/4554302 to your computer and use it in GitHub Desktop.
Save ruby-fu-ninja/4554302 to your computer and use it in GitHub Desktop.
Create attribute accessor's for serialized attributes when using the serialize method in Rails
module SerializedAttrAccessor
module ClassMethods
def define_serialized_attr_accessor(attribute)
self.class_eval %Q{
def #{attribute}=(val)
self.serialized_column[:#{attribute}] = val
end
def #{attribute}
self.serialized_column[:#{attribute}]
end
}
end
def serialized_attr_accessors(*attributes)
serialize :serialized_column, Hash
attributes.each do |attribute|
define_serialized_attr_accessor(attribute)
end
end
end
def serialized_column
super || Hash.new
end
def self.included(base)
base.extend ClassMethods
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment