Sha256: f26be31be723265fce819da5c1f956c21b8cec32668ffd6a2c9948cdb78ee3d1

Contents?: true

Size: 1.54 KB

Versions: 5

Compression:

Stored size: 1.54 KB

Contents

module ServiceController::RestActions
  extend ActiveSupport::Concern

  included do
    respond_to :html
    responders :flash

    if respond_to?(:before_action)
      before_action :initialize_service, only: [:new]
      before_action :initialize_service_for_create, only: [:create]
    else
      before_filter :initialize_service, only: [:new]
      before_filter :initialize_service_for_create, only: [:create]
    end
  end

  def new; end

  def create
    perform
  end

  private

  def perform
    @result = execute_service
    if @result.success?

      if respond_to?(:after_success_location, true)
        redirect_to(after_success_location, notice: success_message)
      else
        flash.now[:success] = success_message
        render :create
      end
    else
      render :new
    end
  end


  def success_message
    t('flash.actions.perform.notice', resource_name: @service.class.model_name.human)
  end

  def execute_service
    @service.send(execute_method)
  end

  def execute_method
    :perform
  end

  def hashified_params
    if permitted_params.respond_to?(:to_h)
      permitted_params.to_h
    else
      permitted_params
    end
  end

  def initialize_service
    @service = service_class.new({}, service_options)
  end

  def initialize_service_for_create
    @service = service_class.new(hashified_params, service_options)
  end

  def service_options
    default_options
  end

  def default_options
    { autosave: true }
  end

  def permitted_params
    raise "You have to implement permitted_params in #{self.class.name}."
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
rails-add_ons-2.1.1 app/concerns/service_controller/rest_actions.rb
rails-add_ons-2.1.0 app/concerns/service_controller/rest_actions.rb
rails-add_ons-2.0.2 app/concerns/service_controller/rest_actions.rb
rails-add_ons-2.0.1 app/concerns/service_controller/rest_actions.rb
rails-add_ons-2.0.0 app/concerns/service_controller/rest_actions.rb