Using structs in Ruby on Rails gives dynamic constant assignment (SyntaxError)

If you want to keep the whole thing neatly inside your index method you could do this:

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

As gunn said, you just can't explicitly assign a constant within a method like that...

This solution is explained more in the ruby docs here, second example on the page.


The error explains what the problem is - you have a constant being assigned in a context that's too dynamic - i.e. inside the index method.

The solution is to define it outside:

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

Tags:

Ruby

Struct