Skip to content

Instantly share code, notes, and snippets.

@sporto

sporto/interactor.rb

Created Jul 22, 2017
Embed
What would you like to do?
A pattern for interactors
class DoSomething
def self.build(dep:)
->(user:) {
self.new(dep: dep, user: user).call
}
end
def initialize(dep:, user:)
@dep = dep
@user = user
end
def call
{
current: report[:current],
previous: report[:previous],
}
end
private
# We should be able to memoize an instance variable
# without worrying about the side effects of this
def report
@report ||= expensive_computation(@user)
end
def expensive_computation(user)
{
current: "current for " + user,
previous: "previous for " + user,
}
end
end
# You can build an interactor injecting dependecies
interactor = DoSomething.build(dep: {})
# And call it with different parameters
puts interactor.call(user: "Sam")
puts interactor.call(user: "Tess")
# Or you can do everything in one
puts DoSomething.new(dep: {}, user: "Sally").call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.