Skip to content

Instantly share code, notes, and snippets.

@krzykamil
Last active April 17, 2023 12:10
Show Gist options
  • Save krzykamil/458939b7f2d4bb9ae2843221a39e85a8 to your computer and use it in GitHub Desktop.
Save krzykamil/458939b7f2d4bb9ae2843221a39e85a8 to your computer and use it in GitHub Desktop.
Current Time Algebraic Effect
require 'dry/effects'
class CurrentTimeMiddleware
include Dry::Effects::Handler.CurrentTime
def initialize(app)
@app = app
end
def call(env)
# It will use Time.now internally once and set it fixed
with_current_time do
@app.(env)
end
end
end
###
class CreateSubscription
include Dry::Efefcts.Resolve(:subscription_repo)
include Dry::Effects.CurrentTime
def call(values)
subscription_repo.create(
values.merge(start_at: current_time)
)
end
end
## Setup
require 'dry/effects'
RSpec.configure do |config|
config.include Dry::Effects::Handler.CurrentTime
config.include Dry::Effects.CurrentTime
config.around { |ex| with_current_time(&ex) }
end
## Change the time
it 'uses current time as a start' do
subscription = create_subscription(...)
expect(subscription.start_at).to eql(current_time)
end
it 'closes a subscription with current time' do
future = current_time + 86_400
closed_subscription = with_current_time(proc { future }) { close_subscription(subscription) }
expect(closed_subscription.closed_at).to eql(future)
end
@krzykamil
Copy link
Author

https://dry-rb.org/gems/dry-effects/0.1/effects/current_time/

This example is great and clear so I did not write my own
It shows connecting two effects, handling and reading the current time effect, and a simple Dependency Injection effect, which we will talk about later

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment