Skip to content

Instantly share code, notes, and snippets.

@rklemme
Created June 22, 2010 08:00
Show Gist options
  • Save rklemme/448155 to your computer and use it in GitHub Desktop.
Save rklemme/448155 to your computer and use it in GitHub Desktop.
class Module
def attr_with_default(name, default = nil, &init)
n = "@#{name}"
define_method name do
instance_variable_get(n) || (init ? init.call(self) : default)
end
attr_writer name
end
end
class Foo
attr_with_default "bar", 123
attr_with_default "baz" do |obj| obj.object_id end
end
f = Foo.new
printf "%-10s %p\n", 'bar', f.bar
f.bar = 99
printf "%-10s %p\n", 'bar', f.bar
printf "%-10s %p\n", 'baz', f.baz
f.baz = 11
printf "%-10s %p\n", 'baz', f.baz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment