Skip to content

Instantly share code, notes, and snippets.

@arya
Created November 18, 2009 18:06
Show Gist options
  • Save arya/238108 to your computer and use it in GitHub Desktop.
Save arya/238108 to your computer and use it in GitHub Desktop.
module User::Extras
# ActiveRecord, at the time of this writing, always writes serialized attributes to the database, even if it hasn't changed.
# See http://github.com/rails/rails/commit/992fda16ed662f028700d63a8dcbd1837f1d58ab for the patch that introduced this.
# So to get around it, we're going to handle the serialization of the extras hash ourselves.
def self.included(klass)
klass.class_eval do
before_save :serialize_extras_attribute
end
klass.extend(ClassMethods)
end
def extras
@extras ||= begin
if self.read_attribute(:extras)
YAML.load(self.read_attribute(:extras))
else
{}
end.with_indifferent_access
end
end
def extras=(*args)
raise "Should never call this, you should only modify keys of the extras hash."
end
def serialize_extras_attribute
write_attribute("extras", @extras.to_hash.to_yaml) if @extras
end
module ClassMethods
def extras_accessor(*args)
args.each do |method|
class_eval <<-METHODS
def #{method}
self.extras['#{method}']
end
def #{method}=(value)
self.extras['#{method}'] = value
end
METHODS
end
end
alias extra_attributes extras_accessor
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment