Rails:在帮助器中的类中访问Cookie

时间:2019-03-16 21:18:50

标签: ruby-on-rails cookies

我在rails助手中有一个ruby类,并且内部,我无法访问ActiveController cookie方法。我看过this question,但它并不能解决我的问题,我也没有做那个家伙,因为我的ruby类在控制器的范围内,只能被它调用。摆脱

的最佳方法是什么
NameError (undefined local variable or method `cookies` for #<CartHelper::CartObject:...>):

app/helpers/cart_helper.rb:##:in `save`
app/helpers/cart_helper.rb:##:in `add_product`
app/controllers/cart_controller.rb:##:in `add`

在我的助手中? (我也对如何使这种更Ruby-y方法更明智的建议持开放态度)

module CartHelper
  class CartObject
    def load (cart)
      # converts from json
    end
    private def save
      cookies.signed.permanent[:cart] = dump
    end
    private def dump
      # converts to json
    end

    def add_product (product)
      # ...
      save
    end
    def remove_product (product)
      # ...
      save
    end
  end
  def get_cart
    return CartObject.new if cookies.signed.permanent[:cart].nil?
    CartObject.load(cookies.signed.permanent[:cart])
  end
end

CartHelper当然包含在应用程序控制器中

class CartController < ApplicationController\
  skip_before_action :verify_authenticity_token, only: [:add]
  def view
    cart = get_cart
    @products = cart.products
  end
  def add # only by ajax
    cart = get_cart
    cart.add_product(Oj.strict_load(params[:product]))
    head 200
  end
  def remove
    cart = get_cart
    cart.remove_product(params['rem'])
    flash['success'] = 'Product removed.'
    redirect_to '/cart'
  end
end

0 个答案:

没有答案