Skip to content

leoncruz/action_service

Repository files navigation

ActionService

A simple rails plugin to create Service Objects

Usage

How to use my plugin.

Installation

Add this line to your application's Gemfile:

gem 'action_service'

And then execute:

$ bundle

Or install it yourself as:

$ gem install action_service

Usage

Define a Service

class UserRegistration < ActionService::Base
  attr_accessor :name, :email, :password

  actions :create_user, :send_welcome_email

  def create_user
    failure errors: user.errors unless user.save
  end

  def send_welcome_email
    UserRegistrationMailer.welcome(to: email).deliver_later

    success user: user
  end

  def user
    @user ||= User.new(attribtues)
  end
end
  1. Create a class that inherits from ActionService::Base

  2. Define attr_accessors. They will be the parameters that the service will receive

  • You can use attributes to access all attr_accessors as a hash
  1. Define actions that the service will execute as a list of symbols. This actions are the methods name on service

  2. Create methods

  3. When a failure occours, calls a failure method passing a hash as argument

  4. For success, calls a success method passing a hash as argument as well

Use the Service

class UsersController < ApplicationController
  def create
    result = UserRegistration.call(**user_params)

    if result.success?
      render json: result.user, status: :created
    else
      render json: result.errors, status: :bad_request
    end
  end

  private

  def user_params
    params.require(:user).permit(:name, :email, :password)
  end
end
  1. Use the call class method to execute and pass parameters

  2. You can use the hash argument passed for the failure and success methods for getting information about your service

  • The keys of hash become instance variables with your values

On service

failure errors: user.errors

Or

failure user_errors: user.errors

Getting the result

result.errors

Or

result.user_errors

The same happend to hash informed on success method

Contributing

Contribution directions go here.

License

The gem is available as open source under the terms of the MIT License.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published