【问题标题】:Can't override Spree's helper's method无法覆盖 Spree 的助手方法
【发布时间】:2019-04-16 08:36:42
【问题描述】:

为什么我的代码没有覆盖 Spree 的代码?

app/helpers/spree/frontend_helper_decorator.rb

Spree::FrontendHelper.module_eval do

    def taxons_tree(root_taxon, current_taxon, max_level = 1)
      return '' if max_level < 1 || root_taxon.children.empty?
      content_tag :ul, class: 'taxons-list' do
        root_taxon.children.map do |taxon|
          css_class = (current_taxon && current_taxon.self_and_ancestors.include?(taxon)) ? 'current' : nil
          content_tag :li, class: css_class do
           link_to(taxon.name, seo_url(taxon)) +
           taxons_tree(taxon, current_taxon, max_level - 1)
          end
        end.join("\n").html_safe
      end
    end

end

【问题讨论】:

  • 您可以尝试将文件重命名为frontend_helper.rb吗?
  • @MrShemek 错误:Circular dependency detected while autoloading constant Spree::FrontendHelper
  • 能否将第一行改为:module Spree::FrontedHelper(删除module_eval块)?
  • @MrShemek 我以前做过。这会导致问题,只有我的自定义方法有效,而 Spree::FrontendHelper 的其他方法无效。
  • @MrShemek 我找到了解决方案,请看我的回答)

标签: ruby-on-rails spree


【解决方案1】:

在上方查看已接受的答案

所以在我将装饰器文件添加到初始化程序后它就起作用了:

spree.rb

require "#{Rails.root}/app/helpers/spree/frontend_helper_decorator.rb"

要添加所有助手装饰器,我使用以下代码:

Dir["#{Rails.root}/app/helpers/spree/*.rb"].each {|file| require file }

更改后别忘了重启服务器!

【讨论】:

    【解决方案2】:

    你的 application.rb 中有这个吗?

    config.to_prepare do
      # Load application's model / class decorators
      Dir.glob(File.join(File.dirname(__FILE__), "../app/**/*_decorator*.rb")) do |c|
        Rails.configuration.cache_classes ? require(c) : load(c)
      end
    
      # Load application's view overrides
      Dir.glob(File.join(File.dirname(__FILE__), "../app/overrides/*.rb")) do |c|
        Rails.configuration.cache_classes ? require(c) : load(c)
      end
    end
    

    【讨论】:

    猜你喜欢
    • 2012-08-12
    • 1970-01-01
    • 2023-03-11
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多