Skip to content

Instantly share code, notes, and snippets.

@r6m
Created January 2, 2017 10:50
Show Gist options
  • Save r6m/2f7fa74eb1b9c062c17daae3820b7408 to your computer and use it in GitHub Desktop.
Save r6m/2f7fa74eb1b9c062c17daae3820b7408 to your computer and use it in GitHub Desktop.
yet another simple serializer for ruby class. you can also access to attr_accessor variable names
module Serializer
def serializables
self.class.instance_variable_get('@serializables')
end
def attr_accessors
self.class.instance_variable_get('@attr_accessors')
end
def self.included(klass)
klass.send :define_singleton_method, :json, ->(*params) do
@serializables ||= []
@serializables.concat params
end
klass.send :define_singleton_method, :attr_accessor, ->(*params) do
@attr_accessors ||= []
@attr_accessors.concat params
super(*params)
end
klass.send :define_method, :get_instance_variable, ->(key) do
self.send key.to_sym
end
end
def to_data
hash = {}
self.class.instance_variable_get('@serializables').each do |k|
hash.merge!({"#{k.to_s}" => self.get_instance_variable(k)})
end
hash
end
end
class User
include Serializer
attr_accessor :username, :full_name, :password
json :username, :fullname
end
u = User.new
u.username = "rezam"
u.full_name = "Reza M"
u.password = "secret"
u.attr_accessors
# => [:username, :full_name, :password]
u.serializables
# => [:username, :full_name]
u.to_data
# => {username: 'rezam', full_name: 'Reza M'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment