ruby-on-railsrubyservice-object

How to display flash messages in rails service object


I want to add service objects in to my controller. Is there any chance to include flash messages in to this service object?

user_stocks_controller

class UserStocksController < ApplicationController
  def create
    @user_stock = UserStocksCreator.new(current_user, params).call
    redirect_to my_portfolio_path
  end
end

service objects user_stocks_creator

class UserStocksCreator
  def initialize(current_user, params)
    @current_user = current_user
    @params = params[:stock_ticker]
  end

  def call
    stock = Stock.find_by_ticker(params)
    if stock.blank?
      stock = Stock.new_from_lookup(params)
      stock.save
    end
    @user_stock = UserStock.create(user: current_user, stock: stock)
    flash[:success] = "Stock #{@user_stock.stock.name} was successfully added to portfolio"
  end

  private

  attr_accessor :current_user, :params
end

With this code I have an error:

undefined local variable or method `flash'


Solution

  • The flash method is only available in the controller. When you want to set the flash in the service object then you need to pass the flash to the service object.

    # in the controller
    def create
      @user_stock = UserStocksCreator.new(current_user, params, flash).call
      redirect_to my_portfolio_path
    end
    
    # in the service
    class UserStocksCreator
      def initialize(current_user, params, flash)
        @current_user = current_user
        @params = params[:stock_ticker]
        @flash = flash
      end
    
      def call
        # unchanged...
      end
    
      private
    
      attr_accessor :current_user, :params, :flash
    end