Skip to content

Instantly share code, notes, and snippets.

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