Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Implementation "#to_h", returning a hash which includes the attribute name and its value
require 'set' # Railsの場合不要
module AttrAccessorExtension
def to_h
Hash[self.class.__send__(:attributes).sort.map { |name| [name, public_send(name)] }]
end
def self.included(klass)
klass.extend(ClassMethods)
end
module ClassMethods
private
def attributes
@attributes ||= superclass.respond_to?(:attributes, true) ? superclass.__send__(:attributes) : Set.new
end
def attr_reader(*names)
super
attributes.merge(names.map(&:to_sym))
end
def attr_accessor(*names)
super
attributes.merge(names.map(&:to_sym))
end
end
end
if $0 == __FILE__
class Hoge
include AttrAccessorExtension
attr_accessor :attr1, :attr2
end
hoge = Hoge.new
hoge.attr1 = 1
hoge.to_h # => {:attr1=>1, :attr2=>nil}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment