在 liquid drop rails 5 内访问当前用户

Access current user within liquid drop rails 5

我目前正在我的应用程序中实施液体模板。作为其中的一部分,我创建了一组液滴 (https://github.com/Shopify/liquid/wiki/Trying-to-Understand-Drops) classes 作为我的模型和模板之间的中间体。我目前正在 rails 5.

上使用设计进行身份验证

在我的产品投放中 class 我希望能够检查我的当前用户是否拥有该产品:

class ProductDrop < Liquid::Drop

  def initialize(model)
    @model = model
  end

  def owned_by_user?
     #somehow access the current_user provided by devise.
  end

end

但一直没弄清楚如何访问用户。

我在 shopify 的这个方法中注意到:https://help.shopify.com/en/themes/liquid/objects/variant#variant-selected 他们能够访问当前的 url 以确定是否选择了变体。我认为如果他们可以访问 url 来访问会话并获取用户标识符来查找用户,也许是可能的。

所以我可以这样做:

def owned_by_user?
   User.find_by_id(session[:user_id]).owns_product?(@model.id)
end

我无法访问会话。有人有什么建议或想法吗?还是我的做法完全错误?

所以在深入研究了 liquid drop 源代码之后。我注意到 drop (https://github.com/Shopify/liquid/blob/master/lib/liquid/drop.rb) 可以访问上下文。我第一次看的时候完全错过了。

所以最终的解决方案是:

首先添加用户,以便它可用于为其呈现视图的控制器操作。然后 liquid 模板处理程序将其添加到上下文中(因此存在于上下文中)

class ApplicationController < ActionController::Base

  before_action :set_common_variables

  def set_common_variables
    @user = current_user # Or how ever you access your currently logged in user
  end

end

将方法添加到产品中以从液体上下文中获取用户

class ProductDrop < Liquid::Drop

  def initialize(model)
    @model = model
  end

  def name
    @model.name
  end

  def user_owned?
    return @context['user'].does_user_own_product?(@model.id)
  end

end

然后将方法添加到用户以检查用户是否拥有该产品:

class UserDrop < Liquid::Drop

  def initialize(model)
    @model = model
  end

  def nick_name
    @model.nick_name
  end

  def does_user_own_product?(id)
    @model.products.exists?(id: id)
  end

end

显然这需要错误处理等等。但希望这对某人有帮助。另外,如果有人知道更好的方法,很想听听。