Dercni
Dercni

Reputation: 1224

Repeated function for every controller action

I have a function that populates an instance variable which is used to display site activity in a side bar.

As the site activity needs to be displayed on almost every controller action I am repeating the code in each controller and calling it from every action. So I have multiple copies of the same function. The activity function is independent of the controller and action.

Obviously this is wrong so my question is where should I place this function.

def activity
  @activity = Activity.all.limit(30)
end

Application Layout

<%= render partial: "shared/activity", collection: @activity %>

Upvotes: 0

Views: 235

Answers (2)

Sachin R
Sachin R

Reputation: 11876

put the method in your application helper file and use direct instead of using as @activity object.

in application_helper.rb

def activity
  Activity.all.limit(30)
end

remove from controller

<%= render partial: "shared/activity" %>

In activity.html.erb

call activity method directly it will give list that you want.

Using above approach remove dependency from controller whenever you call render you don't need to pass @activity explicitly.

Upvotes: 0

cionescu
cionescu

Reputation: 144

You could place this in the ApplicationController. The thing I would do is to use a before_action (http://guides.rubyonrails.org/action_controller_overview.html#filters). A sample would be:

class ApplicationController < ActionController::Base
  before_action :set_activities

  private

  def set_activities
     @activity = Activity.all.limit(30)
  end
end

You also don't need .all.limit you could do .limit right away.

Upvotes: 1

Related Questions