在Ruby on Rails中使用结构体提供动态常量赋值(SyntaxError)

ber*_*kes 24 ruby struct

在我的控制器中,我有以下简化代码:

def index
  @dashboard_items = []
  DashItem = Struct.new(:name, :amount, :moderated)  # Error is here

  [:page, :post].each do |c|
    obj = c.to_s.capitalize.constantize
    @dashboard_items << DashItem.new(c.to_s, obj.count, obj.count_moderated)
  end
end
Run Code Online (Sandbox Code Playgroud)

但是Ruby给出了以下错误:

动态常量赋值(SyntaxError)

在上面标出的线上.

其中,AFAIK,意味着DashItem已经定义了常量.它是否正确?该怎么办呢?

gun*_*unn 49

该错误解释了问题所在 - 您在一个过于动态的上下文中分配了一个常量 - 即在索引方法中.

解决方案是在外面定义它:

DashItem = Struct.new(:name, :amount, :moderated)
def index
  @dashboard_items = []
  ...
Run Code Online (Sandbox Code Playgroud)


Lex*_*xun 14

如果你想在索引方法中整齐地保留整个东西,你可以这样做:

def index
  @dashboard_items = []
  # Set the name of your struct class as the first argument
  Struct.new('DashItem', :name, :amount, :moderated)
  ...
  # Then when you want to create an instance of your structure
  # you can access your class within the Struct class
  @dashboard_items << Struct::DashItem.new(c.to_s, obj.count, obj.moderated)
end
Run Code Online (Sandbox Code Playgroud)

正如gunn所说,你不能在这样的方法中明确地指定常量......

这个解决方案在这里的ruby文档中有更多解释,第二个例子在页面上.