简体   繁体   中英

Passing params in Rails helper class

I am trying to refactor my Rails helpers and move breadcrumbs and navigation menu logic into separate classes. But in these classes I don't have access to params , cookies hashes etc. I think that passing params on and on between different classes is a bad idea. How can I avoid that?
For example I have:

module NavigationHelper

  def nav_item(name, path, inactive = false)
    NavItem.new(params, name, path, inactive ).render
  end

  class NavItem
    include ActionView::Helpers
    include Haml::Helpers

    def initialize(params, name, path, inactive )
      init_haml_helpers
      @params   = params
      @name     = name
      @path     = path
      @inactive = inactive
    end

    def render
      capture_haml do
        haml_tag :li, item_class do
          haml_concat link_to @name, @path
        end
      end
    end

    def item_class
      klass = {class: 'active'}   if active?
      klass = {class: 'inactive'} if @inactive
      klass
    end

    # Class of the current page
    def active?
      slug = @path.gsub /\//, ''
      @params[:page] == slug || @params[:category] == slug
    end
  end
end

I don't think Rails provide any mechanism to access Params out of ActionPack. The way you have done is seems correct to me. You have to pass on params, cookies atleast once to initialize your classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM