Closed eyalev closed 10 years ago
No, sorry. The idea is to remove boilerplate for the most common case, but if you need things like that, or default values etc, just define a regular initializer.
It's mostly that I can't think of a good syntax that isn't too messy or non-obvious. If you can think of something, do suggest it.
Ok, thanks
One thing you can do is to use ||=
or ||
to achieve similar effects. It depends on what you need it for.
class Foo
pattr_initialize :bar
private
def time
@time ||= Time.now
end
def bar
@bar || "default-value"
end
end
Good idea, thanks @joakimk
@henrik Would it be a good idea for attr_initialize
and friends to mix in a module so that you can override #initialize and super
as needed?
@mcmire Hm, yeah, maybe. I generally like the flexibility you get by adding functionality through mixing in modules.
We do support a block syntax to do things after assigning values, e.g.
pattr_initialize :time do
@time ||= Time.now
end
Which could help in some cases. But in this example, you would still need to pass a nil
value when you initialize: it doesn't make the argument optional.
We've considered supporting optional arguments, but it's hard to think of a syntax for that that isn't super messy. Currently considering if we should just hijack block parameters:
pattr_initialize { |time=Time.now| }
Hi,
Is it possible to initialize custom instance variables in addition to using pattr_initialize ?
For example: @time = Time.now
Thanks