显示视图的策略和案例运算符
Policy and case operator for the show view
我的网站上有 3 种类型的用户:
- 访客
- 成员
- VIP会员(User模型中有vip属性)
网站上发布了体育预测,但用户没有相同的权利:
- 访问者只能看到过去的预测
- 会员只能看到下一小时发生的预测
- VIP会员可以看到所有预测。
我做了一个 PredictionPolicy 来定义谁可以看到 Prediction 模型的显示视图。
我想我需要使用 case 运算符来列出不同的场景,但我不知道该怎么做。
这是我开始写的(不起作用):
def show?
x = @record.start_time - Time.now
case x
when -1.0/0 .. 0
User.all
when 0 .. 3600
user
when -1.0/0 .. +1.0/0
user.gold
end
end
end
您知道解决方案吗?
非常感谢
class PredictionPolicy < ApplicationPolicy
def show?
x = @record.start_time - Time.now
case x
when -1.0/0 .. 0
User.all
when 0 .. 3600
user
when -1.0/0 .. +1.0/0
user.vip
end
end
def create?
user.vip
end
def update?
user.team
end
def destroy?
user.team
end
def user_feed?
user.vip
end
def upvote?
user.vip
end
class Scope < Scope
def resolve
if user
if user.vip
scope.all
else
scope.where(status: [:won, :lost, :void])
end
else
scope.where(status: [:won, :lost, :void])
end
end
end
end
你的例子很好地说明了如何使用 scopes。
您应该在 PredictionPolicy
下定义名为 Scope
的子类。实施应如下所示:
class PredictionPolicy
# In this class we define which user can
# see which preditions.
class Scope
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
if user.blank? # guest
scope.where('start_time < ? AND status IN (?)', Time.now, [:won, :lost, :void])
elsif user.vip
scope.all
else
scope.where('start_time < ? AND status IN (?)', Time.now + 1.hour, [:won, :lost, :void])
end
end
end
end
定义策略后,您可以在控制器中使用它:
def index
@predictions = policy_scope(Prediction)
end
我的网站上有 3 种类型的用户:
- 访客
- 成员
- VIP会员(User模型中有vip属性)
网站上发布了体育预测,但用户没有相同的权利:
- 访问者只能看到过去的预测
- 会员只能看到下一小时发生的预测
- VIP会员可以看到所有预测。
我做了一个 PredictionPolicy 来定义谁可以看到 Prediction 模型的显示视图。
我想我需要使用 case 运算符来列出不同的场景,但我不知道该怎么做。
这是我开始写的(不起作用):
def show?
x = @record.start_time - Time.now
case x
when -1.0/0 .. 0
User.all
when 0 .. 3600
user
when -1.0/0 .. +1.0/0
user.gold
end
end
end
您知道解决方案吗?
非常感谢
class PredictionPolicy < ApplicationPolicy
def show?
x = @record.start_time - Time.now
case x
when -1.0/0 .. 0
User.all
when 0 .. 3600
user
when -1.0/0 .. +1.0/0
user.vip
end
end
def create?
user.vip
end
def update?
user.team
end
def destroy?
user.team
end
def user_feed?
user.vip
end
def upvote?
user.vip
end
class Scope < Scope
def resolve
if user
if user.vip
scope.all
else
scope.where(status: [:won, :lost, :void])
end
else
scope.where(status: [:won, :lost, :void])
end
end
end
end
你的例子很好地说明了如何使用 scopes。
您应该在 PredictionPolicy
下定义名为 Scope
的子类。实施应如下所示:
class PredictionPolicy
# In this class we define which user can
# see which preditions.
class Scope
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
if user.blank? # guest
scope.where('start_time < ? AND status IN (?)', Time.now, [:won, :lost, :void])
elsif user.vip
scope.all
else
scope.where('start_time < ? AND status IN (?)', Time.now + 1.hour, [:won, :lost, :void])
end
end
end
end
定义策略后,您可以在控制器中使用它:
def index
@predictions = policy_scope(Prediction)
end