SimpleServices

Installation

SimpleServices is Rails plugin. Install as normal with a plugin:

> script/plugin install http://opensource.thinkrelevance.com/svn/plugins/simple_services/tags/stable/simple_services

Dependencies

SimpleServices relies on Aquarium for method aspecting.

> sudo gem install aquarium

SimpleServices

Creates a simple services layer with automatic transactional demarcation. To use, simply create a folder at app/services, and add classes that derive from Service::Base. That's it. All the methods in the service will be wrapped in a transaction by default. Any exception within that method will rollback the transaction.

Services are singletons to reduce memory overhead. And since they're singletons, they MUST remain stateless.

Example

  # in RAILS_ROOT/app/services
  class AccountService < Service::Base

    def transfer(base_acct, target_acct, amt)
  
      base_acct.balance -= amt
      base_acct.save!
      target_acct.balance += amt
      target_acct.save!
  
    end

  end

  class AccountController < ApplicationController
  
    # adds two methods to instances of this controller:
    #    account_service
    #    user_service
    services :account, :user
  
    def update
      base = Account.find(params[:base_id])
      target = Account.find(params[:target_id])
      # use service.  enjoy transactions.  lather. rinse. repeat.
      account_service.transfer(base, target, params[:amount])
    end
  
  end