Skip to content

Instantly share code, notes, and snippets.

@bswinnerton
Last active April 23, 2016 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bswinnerton/5d08313d14565f614988 to your computer and use it in GitHub Desktop.
Save bswinnerton/5d08313d14565f614988 to your computer and use it in GitHub Desktop.
module SerializableAttributes
extend ActiveSupport::Concern
included do
class << self
attr_reader :serializable_column
end
before_save :update_serializable_column
def self.serialize_attributes(serializable_column = :data)
@serializable_column = serializable_column
yield if block_given?
end
def self.string(*args)
args.each { |attr| create_reader(attr) }
args.each { |attr| create_writer(attr) }
end
# Creates the following method:
#
# def favorite_color
# store['favorite_color']
# end
#
def self.create_reader(attribute)
define_method(attribute) do
store[attribute.to_s]
end
end
# Creates the following method:
#
# def favorite_color=(favorite_color)
# store['favorite_color'] = favorite_color
# end
#
def self.create_writer(attribute)
define_method("#{attribute}=") do |value|
store[attribute.to_s] = value
end
end
end
private
def update_serializable_column
send("#{self.class.serializable_column}=", store.to_json)
end
def store
@store ||= JSON.parse(send(self.class.serializable_column) || "{}")
end
end
class User < ActiveRecord::Base
include SerializableAttributes
serialize_attributes do
string :title, :description
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment