MiniServices is a rails gem that provides a prototype from which to build single-functionality minimalistic services.
Define them like this:
class Service < MiniService::Base
arguments [:required1, :required2], {optional1: 1, optional2: '2'}
private
def perform
return [required1, required2, optional1, optional2]
end
end
You get free readers for every argument defined.
Call the service like this:
# You can ommit optional params
> Service.call required1: 1, required2: 2, optional1: 1
=> [1, 2, 1, '2']
Services are essentially objects whose internal state is never exposed and whose existance is ephimeral. Or in simpler words it is an object that's created to perform an action and then destroyed.
You would use a service to perform an action, but would never store the service's instance.
Use MiniService::Base
as the parent class for your services and make them
simple!
You can write a simple service that takes no argument like so:
class Service < MiniService::Base
private
def perform
# This is your startpoint, put your code in here
return 2 + 2
end
end
You can then call it with .call
like this:
> Service.call
=> 4
Now of course we want to make services take some arguments, so we use the
arguments
method to define both required and optional arguments.
It takes an array of symbols for the name of required parameters
first, and a hash with the default values for optional parameters then.
class Service < MiniService::Base
arguments [:required], {optional: "I'm a default value'}
private
def perform
end
end
Which will let you call your service like this:
Service.call required: "I'm mandatory"
# or like this
Service.call required: "I'm mandatory", optional: "I'm not"
Attribute readers are automatically defined for every argument, so you can use them directly inside perform:
class Service < MiniService::Base
arguments [:string]
private
def perform
return string
end
end
> Service.call string: 'Hola mundo'
=> 'Hola mundo'
If you try to instantiate a MiniService
you will get an error.
class Service < MiniService::Base
private
def perform
end
end
> Service.new
=> NoMethodError
If you really want to create instantiable services -which kind of
defeats the whole purpose of this gem alltogether- you can use
public_class_method :new
to reenable it.
class Service < MiniService::Base
public_class_method :new
private
def perform
end
end
> Service.new
=> #<Service:0x0000000000000001>