Created
July 3, 2010 02:07
-
-
Save kch/462209 to your computer and use it in GitHub Desktop.
generate initializers that just set instance variables without wasting lines
This file contains hidden or 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
#!/usr/bin/env ruby1.9 -ryaml | |
# encoding: UTF-8 | |
class Class | |
def initialize_with_attributes(*attrs) | |
attr_reader *attrs | |
define_method(:initialize) do |*args| | |
attrs.zip(args).each { |attr, v| instance_variable_set("@#{attr}", v) } | |
end | |
end | |
end | |
class Foobar | |
initialize_with_attributes :foo, :bar | |
end | |
fb = Foobar.new('afoo', 'abar') | |
y [fb.foo, fb.bar] | |
### Output: | |
# --- | |
# - afoo | |
# - abar | |
# class Foobar without initialize_with_attributes: | |
class Foobar | |
attr_reader :foo, :bar | |
def initialize(foo = nil, bar = nil) | |
@foo, @bar = foo, bar | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment