Home > Software engineering >  Using a helper method to set an instance variable
Using a helper method to set an instance variable

Time:04-07

I have several controllers that set an instance variable, as follows:

before_action :set_max_steam_pressure

.....

def set_max_steam_pressure
  # and then about a dozen lines of code concluding with
  @max_steam_pressure = Valve.where(id: socket_id).first.pressure
end

This code is repeated in about a dozen controllers.

Is it possible to do this through a helper method, as part of the before_action, without having to repeat the same code in all the controllers? Benefits: less code, and if I have to change something in the future, I would only do it in one place.

CodePudding user response:

You can use "controller concern", for example:

app/controllers/concerns/steam_pressure_setup.rb

module SteamPressureSetup
  extend ActiveSupport::Concern

  included do
    before_action: set_max_stream_pressure
  end

  def set_max_stream_pressure
    # ...
  end
end

Then include it in your controllers which need it.

app/controllers/my_controller.rb

class MyController < ApplicationController
  include SteamPressureSetup

  # ...
end

Ref: https://api.rubyonrails.org/classes/ActiveSupport/Concern.html

  • Related