简体   繁体   English

在Rails助手类中传递参数

[英]Passing params in Rails helper class

I am trying to refactor my Rails helpers and move breadcrumbs and navigation menu logic into separate classes. 我试图重构我的Rails助手,并将面包屑和导航菜单逻辑移到单独的类中。 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. 但是在这些类中,我无法访问paramscookies散列等。我认为在不同的类之间不断传递参数是一个坏主意。 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. 我不认为Rails提供了任何从ActionPack中访问Params的机制。 The way you have done is seems correct to me. 你的做法对我来说似乎是正确的。 You have to pass on params, cookies atleast once to initialize your classes. 您必须传递参数,cookie至少一次来初始化您的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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