3

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
daveomcd
  • 6,367
  • 14
  • 83
  • 137

3 Answers3

4

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
Markus
  • 5,667
  • 4
  • 48
  • 64
0

You can move that method to ApplicationController

class ApplicationController < ActionController::Base

  private

  def set_measurable_summary
    @measurable_summary = @player.measurable_summary
  end
end
Yogesh Khater
  • 1,690
  • 1
  • 15
  • 20
  • 1
    Only is the right way if this method is used in (nearly) all controllers. Otherwise starting to add shared methods for some controllers inside `ApplicationController` opens door to hell when the codebase grows ... – Markus Nov 14 '15 at 18:05
0

You can use extend controller to get parent private method. Please do this:

class Players::WorkoutsController < PlayersController
end
akbarbin
  • 4,985
  • 1
  • 28
  • 31