Skip to content

Instantly share code, notes, and snippets.

@kkismd
Created February 25, 2016 02:19
Show Gist options
  • Save kkismd/f9bf88f7cf4c54533db7 to your computer and use it in GitHub Desktop.
Save kkismd/f9bf88f7cf4c54533db7 to your computer and use it in GitHub Desktop.
module DefaultConstructor
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def constructor(*attributes)
attr_reader *attributes
define_method :initialize do |*attrs|
attributes.zip(attrs).each do |attr, value|
instance_variable_set("@#{attr}", value)
end
end
end
end
end
class Hoge
include DefaultConstructor
constructor :foo, :bar, :baz
end
hoge = Hoge.new(1, 2, 3)
p hoge.foo # => 1
p hoge.bar # => 2
p hoge.baz # => 3
@kkismd
Copy link
Author

kkismd commented Feb 25, 2016

あとアリティのチェックも必要

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment