Skip to content

Instantly share code, notes, and snippets.

@yasaichi
Last active August 29, 2015 14:19
Show Gist options
  • Save yasaichi/b2d1e3d4d4d7a1986660 to your computer and use it in GitHub Desktop.
Save yasaichi/b2d1e3d4d4d7a1986660 to your computer and use it in GitHub Desktop.
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