Status:

ActiveService is a Rails extension that aims at creating reusable, transactional services in your application to make your code more DRY.

Installation

With bundler:

# Gemfile
gem 'active_service'

$ bundle install

or directly

$ (sudo) gem install active_service

Usage

Start by generating a service:

$ rails generate active_service:service payment

This will generate an empty stub for you in app/services:

# app/services/payment_service.rb
class PaymentService < ActiveService::Base
  def do_something_important
    # your important code that should not fuck up comes here
  end
end

If you want to use this service in your controller, just add a makro for it:

# app/controllers/
class PaymentController < ApplicationController
  service :payment

  def crazy_payment_action
    if services(:payment).do_something_important
      flash.info 'epic win!'
    else
      redirect_to :back, :error => 'epic fail!'
    end
  end
end

This makro is also available in the services themselves, so that you can nest them.

Good to know

You can always disable the transactional behavior, which might be useful when nesting services, by using the bang-style method name:

service.do_something_important!

ActiveService will wrap all the methods that you define in your service. If you want to execute them directly you can do this by prefixing them:

service.__do_something_important

Nested Transactions are NOT supported!

Configuration

$ rails generate active_service:config

After running the Rails generator you have a new folder app/services where you can place your services. This folder is added to the rails load-path automagically.

If you do not like this folder have a look at the default configuration which has been generated into an initializer at config/active_service.yml:

path: "lib/services"

More on Transactions

Have a look into the API-Docs for more information about Transactions.