Which controller should I put @notifications in?

Imagine a typical, modern web app - where in the navbar or some navigation element that runs along the top there is a notifications menu where it tells the user how many notifications they have received since last visiting.

It also may have a dropdown menu that they can clear off existing notifications or just view them.

Given that these notifications need to be present across all views, where should I put the logic for that? In my ApplicationController? That feels wrong, for some reason - but I can’t see any other explanation.

Also, should I put the actual partials within the generic /shared/ folder?

For those apps that have a Dashboard controller (i.e. a non-restful resource) that just acts as the central hub for a lot of this info, what’s the best way to approach this? In terms of structuring partials that will be included in the Dashboard.

Edit 1

I have stumbled across the Facade pattern as pointed out by Thoughtbot. But I still have some questions.

In my application.html.erb, I have a partial being rendered - <%= render partial: "shared/navbar" %>. In that partial, I want to be able to call somethings (e.g. that @notifications). How would I access that instance variable and other shared variables/resources on other partials that would be declared in this facades/dashboard.rb?

I’m not 100% clear on the Facade Pattern, however it seems like if, in your controller, you’ve instantiated an object from your Facade class, that you’d have access to the ivars by chaining.

So for example:

# app/facades/dashboard.rb
class Dashboard
  
  def initialize(user)
    @user = user
  end

  def notifications
    @notifications ||= user.notifications
  end

  private

  attr_reader :user

end
class ApplicationController
  before_action :load_dashboard

..
..

  private

  def load_dashboard
    @dashboard = Dashboard.new(current_user)
  end
end

Then in your view call this:


@dashboard.notifications

I’m not sure if that answers your question; let me know how it goes! Also, there may be some performance implications on calling load_dashboard on each request as I’m doing here. I would definitely look into caching that so you’re loading the notifications from redis/memcache rather than actually doing the call with each request. With Russian Doll, caching should be simple for that, but you’ll potentially need to skip that before_action if the cache is not busted. That’s a topic for another discussion I think…

Brian