Created
June 19, 2014 02:24
-
-
Save AfonsoTsukamoto/488bce2ff749cc978433 to your computer and use it in GitHub Desktop.
[Ruby] A intializer
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
# Found here: http://c2.com/cgi/wiki?PythonRubyInitializer | |
class Class | |
def initializer(*args, &b) | |
define_method(:__init_proc) {b} | |
params = args.join(", ") | |
vars = args.collect{|a| "@#{a}"}.join(", ") | |
class_eval <<-EOS | |
def initialize(#{params}) | |
#{vars} = #{params} | |
instance_eval &__init_proc | |
end | |
EOS | |
end | |
end | |
#This lets me write code like: | |
class Person | |
initializer(:name, :age, :gender) do | |
puts "Do more initialization for #{@name}" | |
end | |
end | |
#instead of: | |
class Person | |
def initialize(name, age, gender) | |
@name, @age, @gender = name, age, gender | |
puts "Do more initialization for #{@name}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment