Skip to content

Instantly share code, notes, and snippets.

@wojtha
Created April 8, 2014 16:54
Show Gist options
  • Select an option

  • Save wojtha/10155351 to your computer and use it in GitHub Desktop.

Select an option

Save wojtha/10155351 to your computer and use it in GitHub Desktop.
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