如何从主 Rails 应用程序访问 Spree 的 link_to_cart 函数
我正在一个现有的 Rails 应用程序中构建一个狂欢商店,我需要从 Spree 引擎外部访问 link_to_cart
.
I am building a spree shop into an exiting Rails application, and I need to access link_to_cart
from outside of the Spree engine.
link_to_cart
可在此处找到:spree/core/app/helpers/spree/base_helper.rb
link_to_cart
can be found here: spree/core/app/helpers/spree/base_helper.rb
由于我修改了link_to_cart
中的样式,所以我还创建了:
Since I have modified the styling in link_to_cart
, I also created:
#helpers/spree/base_helper_decorator.rb
module Spree
module BaseHelper
def link_to_cart(text = nil)
text = text ? h(text) : Spree.t('cart')
css_class = nil
if simple_current_order.nil? or simple_current_order.item_count.zero?
text = "#{text}: (#{Spree.t('empty')})"
css_class = 'empty'
else
text = "<i class='fa fa-shopping-cart'></i> #{text}: (#{simple_current_order.item_count}) <span class='amount'>#{simple_current_order.display_total.to_html}</span>".html_safe
css_class = 'full'
end
link_to text.html_safe, spree.cart_path, :class => "cart-info #{css_class} btn btn-small btn-success pull-right", style: "margin-left:10px;"
end
end
end
我曾尝试在引擎之外做类似 Spree::BaseHelper.link_to_cart 之类的事情,但我不断收到 未定义的局部变量或方法 'link_to_cart'
I have tried doing stuff like Spree::BaseHelper.link_to_cart outside of the engine, but I keep getting undefined local variable or method 'link_to_cart'
我在 不同的 StackOverflow 问题,看起来很有希望,但我不知道如何根据我的需要修改它:
I found this on a different StackOverflow question, and it seems promising, but I'm not sure how to modify it for my needs:
module MyEngine
class Engine < Rails::Engine
initializer 'my_engine.action_controller' do |app|
ActiveSupport.on_load :action_controller do
helper MyEngine::ImportantHelper
end
end
end
end
好的,感谢 Ben 让我走上正轨.这是我的解决方案:
Ok, thanks Ben for getting me on the right track. Here was my solution:
# class ApplicationController < ActionController::Base
include Spree::Core::ControllerHelpers::Order
include Spree::Core::ControllerHelpers::Auth
helper Spree::BaseHelper
helper Spree::StoreHelper
更新
我遇到了在引擎之外未定义 current_store
的问题.我不确定如何正确解决这个问题,但与此同时,我刚刚添加了以下内容以阻止狂欢调用 current_store:
I ran into an issue with current_store
being undefined outside of the engine. I'm not sure how to solve this properly, but in the meantime I've just added the following to stop spree from calling current_store:
module Spree
module Core
module ControllerHelpers
module Order
def current_order_params
{ currency: current_currency, guest_token: cookies.signed[:guest_token], store_id: Spree::Store.first, user_id: try_spree_current_user.try(:id) }
end
end
end
end
end
还有 helper Spree::StoreHelper
似乎不再需要显示购物车按钮和当前订单..
Also helper Spree::StoreHelper
seems to no longer be required to display the cart button and current orders..