Rails: How to access the current controller in Observer?

I need to access the current controller or send a notification from the observer method.

class SomeObserver < ActiveRecord::Observer
    observe :some_model
    cattr_accessor :current_controller

    def after_create(record)
        ...
        current_controller.flash[:notice] = "Some message!"
    end
end

class ApplicationController < ActionController::Base
    before_filter do
        SomeObserver.current_controller = self
    end
    ...
end
+5
source share
4 answers

As others have stated, access to the controller from an observer somewhat violates the MVC principle. Also, these answers correspond to your specific use case.

But , if you need a more general solution, you can try to customize the way the Rails Blenders are .

Sweepers are ordinary observers, but they provide access to the controller if the observer is called from the controller.

- , , , (.. Singleton)

, :

  • , .
  • singleton around_filter :

    class ApplicationController < ActionController::Base
      around_filter MyObserver.instance #, only: [...]
    end
    
  • :

    attr_accessor :controller
    
    def before(controller)
      self.controller = controller
      true #Don't forget this!
    end
    
    def after(controller)
      self.controller = nil
    end
    

. controller nil, .

+4

Observer MVC. , MVC, - flash[:notice] SomeModel.create().

+2

? , , .

application_helper, - diplays.

def show_flash
[:notice, :error, :warning].collect do |key|
  content_tag(:div, flash[key], :id => key, :class => "flash flash_#{key}") unless   flash[key].blank?
end.join
end

<% show_flash %>

, , - , , , .

flash[:notice] = "Some message!"
+1

There is no connection between observers and controllers in Rails, and I'm afraid that you will not achieve your goal in the standard way. However, I suggest using threads to achieve this.

0
source

All Articles