benhamill / assembler

Block-based initializers for your Ruby objects.
https://github.com/benhamill/assembler#readme
MIT License
1 stars 0 forks source link

Think about lazy default evaluation #6

Open kerinin opened 10 years ago

kerinin commented 10 years ago

I can think of two situations where default values might want to be evaluated when an instance is created: defaults which are expensive/side-affecting to create and defaults which are dependent on other values in the constructor:

class Foo
  def initialize(options={})
    @redis = options[:redis] || Redis.new(host: options[:host])
    @dependent = options[:dependent] || @redis.host
  end
end

(That's not a good example of dependent defaults, but you probably know what I'm referring to).

Do we care about supporting this? One solution is to allow nil values and to provide custom accessors:

class Foo
  assemble_from redis: nil, dependent: nil

  def redis
    @redis ||= Redis.new(host: host)
  end

  def dependent
    @dependent ||= redis.host
  end
end

IDK

benhamill commented 10 years ago

The latter is the method I put in the new README stuff in #3 (here). Which is a reasonable hack. I'm not sure how else to do it, since Ruby's going to evaluate the arguments before they're ever passed to assemble_with.

I guess we could make assemble_with take a block and... yield some builder object that has a method on it that you call for each argument...? That seems really heavy-weight, though.

I think I'm with you, on this: IDK. Seems legit, but I don't see a clear way forward.