Created
March 9, 2016 14:57
-
-
Save torarnv/2a3ab96a49d3e388b863 to your computer and use it in GitHub Desktop.
This file contains 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
module NamedInitialize | |
def initialize(*parameters) | |
method(__method__).parameters.each do |type, k| | |
next unless type == :key | |
v = eval(k.to_s) | |
next if v.nil? | |
send("#{k}=", v) # Nope | |
instance_variable_set("@#{k}", v) # Nope | |
end | |
end | |
end | |
class Foo | |
include NamedInitialize | |
attr_accessor :bar, :baz, :biz | |
def initialize(name, bar: nil, baz: nil, biz: nil) | |
@name = name | |
super | |
puts self.baz | |
# This works: | |
# method(__method__).parameters.each do |type, k| | |
# next unless type == :key | |
# v = eval(k.to_s) | |
# instance_variable_set("@#{k}", v) unless v.nil? | |
# end | |
end | |
end | |
f = Foo.new("foo", baz: 42) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment