Last active
April 23, 2016 16:50
-
-
Save bswinnerton/5d08313d14565f614988 to your computer and use it in GitHub Desktop.
This file contains 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 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 |
This file contains 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
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