| 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