Last active
August 29, 2015 14:17
-
-
Save icheishvili/38626aed219ea753cd89 to your computer and use it in GitHub Desktop.
This is the best serialization that I've been able to come up with after dealing with all kinds of gems and frustration
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 EasySerialization | |
extend ActiveSupport::Concern | |
included do | |
self.class_attribute :serialization_config | |
self.serialization_config = Hash.new { |h, k| h[k] = [] } | |
end | |
def serializable_hash(opts={}) | |
opts ||= {} | |
set = opts.fetch(:set, :default) | |
set = :default unless self.serialization_config[set].present? | |
result = {} | |
self.serialization_config[set].each do |key| | |
value = self.send(key) | |
result[key] = | |
if value.is_a?(ActiveRecord::Base) | |
value.serializable_hash(opts) | |
else | |
value | |
end | |
end | |
result | |
end | |
module ClassMethods | |
def configure_for_serialization(*keys) | |
set = :default | |
if keys.last.respond_to?(:each_pair) | |
set = keys.last.fetch(:set, :default) | |
keys = keys[0..-2] | |
end | |
self.serialization_config[set].concat(keys) | |
end | |
end | |
end | |
### USAGE ### | |
class Foo < ActiveRecord::Base | |
... | |
configure_for_serialization :id, :name, :url | |
configure_for_serialization :id, :name, :contacts, set: :compact | |
configure_for_serialization :id, :url, :whatever_else, set: :api | |
... | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment