David Tuite
David Tuite

Reputation: 22643

Expose controller's class method to view helper method?

How do I make the following method available in the view layer?

# app/controllers/base_jobs_controller.rb
class BaseJobsController < ApplicationController
  def self.filter_name
    (controller_name.singularize + "_filter").to_sym
  end
end

I want to use it in a view helper like this:

module ApplicationHelper
  def filter_link(text, options = {})
    # Need access to filter_name in here....
  end
end

Upvotes: 0

Views: 903

Answers (1)

deefour
deefour

Reputation: 35360

Instead of helper_method, I prefer to include such functionality in a module.

module BaseJobsHelp
  def filter_name
    (controller_name.singularize + "_filter").to_sym
  end
end

Then include the module in the BaseJobsController and ApplicationHelper.

class BaseJobsController < ApplicationController
  include BaseJobsHelp

  # ...
end


module ApplicationHelper
  include BaseJobsHelp

  def filter_link(text, options = {})
    # You can access filter_name without trouble
  end
end

Depending on the content of your methods in the module, you may need to use an alternative method to access certain data (ie. the current controller's name).

Upvotes: 2

Related Questions