Skip to content

Instantly share code, notes, and snippets.

@tonytonyjan
Last active July 20, 2016 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonytonyjan/39d977ac1a32a2b02c0d459819f85086 to your computer and use it in GitHub Desktop.
Save tonytonyjan/39d977ac1a32a2b02c0d459819f85086 to your computer and use it in GitHub Desktop.
Minimal service object implementation
class Interactor
attr_reader :error
def self.perform(*args)
new(*args).tap { |interactor| catch(:fail) { interactor.perform } }
end
def success?
@error.nil?
end
def fail!(msg)
@error = msg
throw :fail
end
def perform
raise NotImplementedError
end
end
require 'interactor'
class Double < Interactor
attr_reader :number # attributes which want to be exposed
def initialize(number)
@number = number
end
def perform
fail!("unable to double `#{@number}`") unless @number.respond_to? :*
@number *= 2
end
end
double = Double.perform(123)
double.success? # => true
double.number # => 246
double = Double.perform(:abc)
double.success? # => false
double.error # => "unable to double `abc`"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment