Search code examples
ruby-on-railscontrolleractionnested-resources

In Rails, how can I share a private method to nested controllers?


I have a resource of Player that has various nested resources, such as: Measurable and Workout.

I have a variable that is used int he Player's header on their pages and it has a variable I need to be set whether I'm accessing an action from the Player_Controller or from one of the other nested resources controllers. How can I dry up my code to add that variable somewhere so that I don't have to include the same like of code in every controller... as shown below:

PlayerController

class PlayersController < ApplicationController
   before_action :set_measurable_summary

   #...

   private
     def set_measurable_summary
       @measurable_summary = @player.measurable_summary
     end
end

WorkoutController

class Players::WorkoutsController < ApplicationController
   before_action :set_measurable_summary

   #...

   private
     def set_measurable_summary
       @measurable_summary = @player.measurable_summary
     end
end

Solution

  • This can be easily done with a concern:

    # app/controllers/concerns/measurable_summary.rb
    
    module MeasurableSummary
      extend ActiveSupport::Concern
    
      included do
        before_action :set_measurable_summary
      end
    
      private
    
      def set_measurable_summary
        @measurable_summary = @player.measurable_summary
      end
    end
    

    Then include it into your controllers:

    class PlayersController < ApplicationController
      include MeasurableSummary
      ...
    end
    
    class Players::WorkoutsController < ApplicationController
      include MeasurableSummary
      ...
    end