Skip to content

Instantly share code, notes, and snippets.

@Bhacaz
Created May 7, 2019 19:00
Show Gist options
  • Save Bhacaz/1d0258c0089a3dbc04cdcd9e69ca568f to your computer and use it in GitHub Desktop.
Save Bhacaz/1d0258c0089a3dbc04cdcd9e69ca568f to your computer and use it in GitHub Desktop.
[Ruby] Example of using class attributes
require_relative 'user'
require_relative 'user_serializer'
user = User.new('Hello', 'World', '21')
puts UserSerializer.new(user).serialize
# => {:display_name=>"Hello World", :age=>"21 years old"}
class SerializableAttribute
attr_reader :attribute, :block
def initialize(attribute, &block)
@attribute = attribute
@block = block
end
end
require 'active_support/concern'
require_relative 'serializable_attribute'
module Serializer
extend ActiveSupport::Concern
class_methods do
attr_accessor :attributes_to_serialize
def attribute(name, &block)
self.attributes_to_serialize ||= []
self.attributes_to_serialize << SerializableAttribute.new(name, &block)
end
end
attr_reader :object
def initialize(object)
@object = object
end
def serialize
self.class.attributes_to_serialize.each_with_object({}) do |attribute, result|
result[attribute.attribute] =
if attribute.block
object.instance_eval(&attribute.block)
else
object.send(attribute.attribute)
end
end
end
end
class User
attr_reader :last_name, :first_name, :age
def initialize(first_name, last_name, age)
@first_name = first_name
@last_name = last_name
@age = age
end
def display_name
"#{first_name} #{last_name}"
end
end
require_relative 'serializer'
class UserSerializer
include Serializer
attribute :display_name
attribute :age do |object|
"#{object.age} years old"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment