Skip to content

Instantly share code, notes, and snippets.

@kch
Created July 3, 2010 02:07
Show Gist options
  • Save kch/462209 to your computer and use it in GitHub Desktop.
Save kch/462209 to your computer and use it in GitHub Desktop.
generate initializers that just set instance variables without wasting lines
#!/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