user534498
user534498

Reputation: 3984

Rails: where does the @controller come from?

I am working on an old plugin "menu_helper" (legacy code uses it).

https://github.com/pluginaweek/menu_helper

The main entrance of this library is as follows,

module PluginAWeek
  module MenuHelper
    def menu_bar(options = {}, html_options = {}, &block)
      puts @controller.class
      MenuBar.new(@controller, options, html_options, &block).html
    end
  end
end

ActionController::Base.class_eval do
  helper PluginAWeek::MenuHelper
end

The code works in rails 2.3.5 without problem but fails in 4.2.6.

When I puts @controller.class, in 2.3.5, it will always return the current controller that is using this library, but in 4.2.6 it will be NillClass.

So where does this @controller come from? How do I modify in 4.2.6 to make it work.

Note 1: to use this, I just need to call

html = menu_bar(options,:id => 'menuid')

No any controller is passed in.

Note 2: I am currently running it on controller test.

Thanks.

Upvotes: 0

Views: 58

Answers (1)

born4new
born4new

Reputation: 1687

First of all, I would not use a gem that has not been maintained in the past 5 years and that the master build is currently failing. I'd try to find a well-maintained alternative or if the gem is small enough, to redo it myself.

This being said, menu_helper seems to use this variable: https://github.com/pluginaweek/menu_helper/blob/master/lib/menu_helper/menu.rb#L51

If you want to make it work, do a before_action that would instantiate this variable with the current controller:

before_action :set_legacy_controller

def set_legacy_controller
  @controller = controller
end

Upvotes: 1

Related Questions