Rails 5:如何干燥多个条件

时间:2018-02-21 22:39:22

标签: ruby-on-rails

我有很多用户类型,它们在视图中都显示不同的内容:

- if current_user.type == 'newbie' || current_user.type == 'super_admin'
  | Button A
- if current_user.type == 'regular' || current_user.type == 'experienced' || current_user.type == 'admin' || current_user.type == 'super_admin'
  | Button B
- if current_user.type == 'experienced' || current_user.type == 'manager' || current_user.type == 'admin' || current_user.type == 'super_admin'
  | Button C
... 

我试图通过定义常见条件来缩短它:

application_controller.rb

def user_is_admin
  current_user.type == 'admin' || current_user.type == 'super_admin'
end

视图

- if current_user.type == 'regular' || current_user.type == 'experienced' || user_is_admin
  | Button B

但是我收到了一个错误:

Did you mean?  user_signed_in?

3 个答案:

答案 0 :(得分:1)

作为一个快速解决方案,如下所示:

- if ['newbie', 'super_admin'].include?(current_user.type)
  | Button A
- if ['regular', 'experienced', 'admin'].include?(current_user.type)
  | Button B
- if ['experienced', 'manager', 'admin'].include?(current_user.type)
  | Button C

为了跟进Shiko的答案,我不会亲自将这个逻辑放在模型中,因为我严格限制模型的数据访问(这是业务逻辑)。但是,这是个人偏好的问题。

相反,我很想把它放在decorator中。但那是一个较长时间的讨论。

答案 1 :(得分:0)

正如@jvillian提到Sub CopyUnique() Dim s1 As Worksheet, s2 As Worksheet, FirstEmptyRow As Long, expCol As Long Set s1 = ActiveSheet Set s2 = Sheets("Products") Range("A:A").Cells.Name = "types" expCol = Range("types").Column FirstEmptyRow = Cells(Rows.Count, expCol).End(xlUp).Row + 1 s1.Range("C4:C33").Copy s2.Range(FirstEmptyRow) s2.Range("Products").Column.RemoveDuplicates Columns:=1, Header:=xlNo End Sub ,还有正则表达式选项

.include?

答案 2 :(得分:0)

要正确实现问题中的代码,您需要将代码添加到模型而不是控制器,如下所示:

class User
  def is_admin
    # by the way, type is a reserver word in AR
    type == 'admin' ||  type == 'super_admin'
  end
end

<强> NB:
您可以从 Controller 类访问 application_controller 方法,因为它们从应用程序控制器继承