0.0
No release in over 3 years
Services do one thing and then vanish, POOF!~
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Runtime

 Project Readme

MiniService Gem Version

MiniServices is a rails gem that provides a prototype from which to build single-functionality minimalistic services.

TL;DR

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']

Service Pattern

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.

Usage

Use MiniService::Base as the parent class for your services and make them simple!

Simple Service with no arguments.

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

Service with arguments

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'

Making .new public again

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>