This is how I usually write use-cases/service objects:
class UserRegistrationForm
def self.call(access_code)
new(access_code).call
end
def initialize(access_code)
@access_code = access_code
end
def call
...do stuf...
end
private
..more private methods..
attr_reader :access_code
end
Recently started to use this gem: attr_extras
The gem provides a couple of cool boilerplate cutdowns, the best thing being the method_object
:
The method_object
method does three things:
- creates an initializer that takes in the argument you've passed it, in this case, the
user
, and assigns it to an instance variable@user
- creates a private reader for that argument.
- creates a class level
call
method that instantiates the object and calls thecall
instance method.
Replace the upper piece of code with this:
class UserRegistrationForm
method_object :access_code
end
Benefits:
- Shorter, remove boilerplate code
- Easier to stub out:
- Stubbing out a instance method:
allow_any_instance_of(Widget).to receive(:name).and_return("Wibble")
- Stubbing out a class method
allow(Widget).to receive(:name).and_return("Wibble")
- Stubbing out a instance method: