Skip to content

Instantly share code, notes, and snippets.

@torarnv
Created March 9, 2016 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torarnv/2a3ab96a49d3e388b863 to your computer and use it in GitHub Desktop.
Save torarnv/2a3ab96a49d3e388b863 to your computer and use it in GitHub Desktop.
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