0

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

This is ensentially just a module mixin - aka horizontal inheritance. "controller concern" is somewhat nonsensical as there is no difference between this and any other type of module besides that the concerns folders are autoloading roots where Rails encourages you to put miscellanceus junk.
Yea, the "controller concern" is just a concern and in fact you can use them not only in controllers but anywhere else duo to autoload. But if the code in concern is only for controller usage, we prefer to put them in "app/controllers/concerns" just for clarification.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.