Skip to content

Instantly share code, notes, and snippets.

@AfonsoTsukamoto
Created June 19, 2014 02:24
Show Gist options
  • Save AfonsoTsukamoto/488bce2ff749cc978433 to your computer and use it in GitHub Desktop.
Save AfonsoTsukamoto/488bce2ff749cc978433 to your computer and use it in GitHub Desktop.
[Ruby] A intializer
# 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