amethyst
amethyst copied to clipboard
Can't use an array as a view variable
Though the actual error might be "can't run methods on objects in templates".
# Controller
class MyController < Base::Controller
actions :index
view "index", "#{__DIR__}/../views/ragas"
def index
@array = [1,2,3]
render "index"
end
end
# index.ecr
<%= array.length %>
Error:
Error: instance variable '@array' of MyController was not initialized in all of the 'initialize' methods, rendering it nilable
Though if I just have <%= array %>
in the view that compiles and renders just fine...
What's up?
@dbackeus, What's up is that @array
was not initialized outside of the index def, this means if some other method,function,etc.. will render index, @array
wont be available and will result in nil.
you can do something like this:
# Controller
class MyController < Base::Controller
actions :index
@array = [] of Int32
view "index", "#{__DIR__}/../views/ragas"
def index
@array = [1,2,3]
render "index"
end
end
# index.ecr
<%= array.length %>
This should work as @array
will always be initialized
Thanks for the help, I can compile and render now :)
Hope there will be a work around or cleaner solution for this in the future.
In rails it's discouraged using instance variables in views. I would like to see solution similar to Decent Exposure
Though avoiding instance vars in rails is hardly an accepted best practice. I do agree that something like decent exposure or simply passing the objects down via the render method would be nicer than having to declare instance variables to avoid the nil issue.