Created
July 10, 2013 14:11
-
-
Save saturnflyer/5966613 to your computer and use it in GitHub Desktop.
Dynamically defining the initialize method and setting the arity.
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
class Something | |
def self.init(*init_args) | |
# this works but... | |
define_method(:initialize){|*args| | |
# arity is -1 | |
} | |
class_eval %Q< | |
def initialize(#{*init_args}) | |
# this doesn't work | |
end | |
> | |
end | |
end | |
# Here I want arity of :initialize to be 2 | |
class Special < Something | |
init(:one, :two) | |
end | |
# And here I want arity of :initialize to be 3 | |
class Other < Something | |
init(:one, :two, :three) | |
end |
class Something
def self.init(*init_args)
define_method(:initialize) do |*args|
# TODO: check args, raise similar exception as Ruby
init_args.zip(args) do |name, value|
instance_variable_set("@#{name}", value)
end
end
end
end
# And here I want arity of :initialize to be 3
class Other < Something
init(:one, :two, :three)
end
o = Other.new("one", "two", "three")
puts o.inspect
# #<Other:0x007fbbc40592b8 @one="one", @two="two", @three="three">
thanks guys! @mulder's comment work. I wasn't joining the args
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You'r forgetting class_eval takes a string...