barsoom / attr_extras

Takes some boilerplate out of Ruby with methods like attr_initialize.
MIT License
560 stars 31 forks source link

Initializing custom variables #4

Closed eyalev closed 10 years ago

eyalev commented 10 years ago

Hi,

Is it possible to initialize custom instance variables in addition to using pattr_initialize ?

For example: @time = Time.now

Thanks

henrik commented 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.

eyalev commented 10 years ago

Ok, thanks

joakimk commented 10 years ago

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
eyalev commented 10 years ago

Good idea, thanks @joakimk

mcmire commented 9 years ago

@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?

henrik commented 9 years ago

@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| }