dry-rb / dry-effects

Algebraic effects in Ruby
https://dry-rb.org/gems/dry-effects/
MIT License
112 stars 20 forks source link

Handler mixin #11

Closed flash-gordon closed 5 years ago

flash-gordon commented 5 years ago

Add handler mixin

Now we can introduce and eliminate effects with a nicer API

class GetTimestamp
  include Dry::Effects[:current_time]

  def call
    # effect introduction
    { executed_at: current_time }
  end
end

include Dry::Effects::Handler[:current_time, as: :with_time]

def call
  op = GetTimestamp.new.freeze # op is immutable
  # effect elimination
  with_time.(Time.now) { op.() } # one time value
  with_time.(Time.now + 10) { op.() } # anothe time value
end

I'm thinking about replacing [] with () since it's unlikely we want to include many handlers at once. OTOH adding multiple effects makes sense so having [] may be reasonable for consistency.