我们,首先让我告诉你我是狂热的新手,所以我的问题对大多数人来说可能听起来很愚蠢。我想自定义例如home_controller.rb中的“index”方法,我知道正确的方法是使用装饰器。所以我创建了这个文件app / controller / home_controller_decorator.rb。我在那里
#app / controller / home_controller_decorator.rb
HomeController.class_eval do
def index
# Empty method
end
end
原始的狂欢索引方法看起来像
def index
@searcher = Spree::Config.searcher_class.new(params)
@products = @searcher.retrieve_products
respond_with(@products)
end
我希望当我重新添加_decorator重启服务器时,它会在主页上显示没有产品,或者会崩溃。当应用这个装饰器并启动服务器时,我收到此消息
agop@linux-as2q:~/Desktop/spp> rails server -p 3000
/home/agop/Desktop/spp/app/controllers/home_controller_decorator.rb:1:in `<top (required)>': uninitialized constant Spree::BaseController (NameError)
from /home/agop/Desktop/spp/lib/spree_site.rb:5:in `block in <class:Engine>'
from /home/agop/Desktop/spp/lib/spree_site.rb:4:in `glob'
from /home/agop/Desktop/spp/lib/spree_site.rb:4:in `<class:Engine>'
from /home/agop/Desktop/spp/lib/spree_site.rb:2:in `<module:SpreeSite>'
from /home/agop/Desktop/spp/lib/spree_site.rb:1:in `<top (required)>'
from /home/agop/Desktop/spp/config/application.rb:11:in `<class:Application>'
from /home/agop/Desktop/spp/config/application.rb:10:in `<module:Spp>'
from /home/agop/Desktop/spp/config/application.rb:9:in `<top (required)>'
from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.9/lib/rails/commands.rb:28:in `require'
from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.9/lib/rails/commands.rb:28:in `block in <top (required)>'
from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.9/lib/rails/commands.rb:27:in `tap'
from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.9/lib/rails/commands.rb:27:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
我可能不会像spree期望的那样编写装饰器。在home_controller.rb索引方法上应用此装饰器的正确方法是什么?
答案 0 :(得分:6)
这是因为HomeController
继承自Spree::BaseController
,由于某些未知原因,此时未加载require 'spree/base_controller'
。您应该能够通过将{{1}}放在装饰器的顶部来修复它。
您能否在http://github.com/spree/spree上提交GitHub问题?对于遇到这个问题的其他人来说也会有所帮助。
答案 1 :(得分:0)
ActiveSupport::Concern是一种装饰现有类的简洁方法。
但请注意,缓存不会在开发模式下缓存,因此您需要在config / environments / development.rb中添加类似下面的代码,以确保您的装饰方法持续存在。
config.to_prepare do
#SomeModel.send(:include, SomeDecorator)
end
Here有关详细信息。