In my controller I have the following simplified code:
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
But Ruby gives the following error:
dynamic constant assignment (SyntaxError)
on the line marked above.
Which, AFAIK, means that the constant DashItem is already defined. Is this correct? And what to do about it?
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: