Created
April 8, 2014 16:54
-
-
Save wojtha/10155351 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module ActsAsJSONStore | |
| def self.included base | |
| base.extend ClassMethods | |
| end | |
| module ClassMethods | |
| attr_reader :fields_acting_as_json_store | |
| # Declare a list of attributes in a model to act as JSON store. | |
| # @param [Symbol, ...] The list of attributes. | |
| def acts_as_json_store *attributes | |
| (((@fields_acting_as_json_store ||= []) << attributes).flatten!).uniq! | |
| attributes.each do |column| | |
| define_method column do | |
| JSON.parse(self[column]) rescue self[column] | |
| end | |
| define_method :"#{column}=" do |value| | |
| self[column] = value.kind_of?(Enumerable) ? value.to_json : value | |
| end | |
| end | |
| end | |
| end | |
| end | |
| ActiveRecord::Base.send(:include, ActsAsJSONStore) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment