在RubyonRails中使用结构提供了动态常量赋值(SyntaxError)

在RubyonRails中使用结构提供了动态常量赋值(SyntaxError),ruby,struct,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.coun

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

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
def索引
@仪表板项目=[]
DashItem=Struct.new(:name,:amount,:moderated)#此处有错误
[:page,:post].每个人都做|
obj=c.to_.s.capitalize.constantize

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

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

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

如果您想将整个内容整齐地保存在索引方法中,您可以这样做:

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
def索引
@仪表板项目=[]
#将struct类的名称设置为第一个参数
新结构('DashItem',:名称,:金额,:缓和)
...
#然后,当您要创建结构的实例时
#您可以在Struct类中访问您的类
@仪表板项目如果(在某些情况下)您开始得到
警告:在使用Lexun的答案时重新定义常量结构…
,然后添加条件
,除非定义了Struct::const\u?“DashItem'
可能会有所帮助

def index
  @dashboard_items = []
  # Set the name of your struct class as the first argument
  Struct.new('DashItem', :name, :amount, :moderated) unless Struct::const_defined? 'DashItem'
  ...
  # 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
def索引
@仪表板项目=[]
#将struct类的名称设置为第一个参数
除非定义了Struct::const_,否则结构为new('DashItem',:name,:amount,:moderated)DashItem'
...
#然后,当您要创建结构的实例时
#您可以在Struct类中访问您的类

@dashboard_items这里的另一个简单选项是在动态设置中分配和实例化结构时使用局部变量而不是常量:

def index
  # ...
  dash_item = Struct.new(:name, :amount, :moderated)  

  # ...
    @dashboard_items << dash_item.new( ... )
  # ...
end    
def索引
# ...
破折号项目=结构新(:名称,:金额,:缓和)
# ...

@仪表板项目侧注:空数组+每个+附加=映射可能的重复项