Last active
August 29, 2015 14:11
-
-
Save att14/04f1717f1e3c0eb50837 to your computer and use it in GitHub Desktop.
Macro for adding an `initialize` function and creating `attr_reader`s for each variable passed.
This file contains hidden or 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
class Object | |
def self.init(*names) | |
define_method(:initialize) do |*args| | |
names.zip(args).each do |name, arg| | |
instance_variable_set("@#{name}", arg) | |
end | |
singleton_class.class_eval do | |
attr_reader *names | |
end | |
end | |
end | |
end | |
class Test | |
init :foo | |
end | |
p Test.new(:bar).foo == :bar |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment