amethyst icon indicating copy to clipboard operation
amethyst copied to clipboard

Can't use an array as a view variable

Open dbackeus opened this issue 8 years ago • 4 comments

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 avatar Jul 20 '15 12:07 dbackeus

@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

bararchy avatar Jul 20 '15 12:07 bararchy

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.

dbackeus avatar Jul 20 '15 14:07 dbackeus

In rails it's discouraged using instance variables in views. I would like to see solution similar to Decent Exposure

dziulius avatar Jul 20 '15 15:07 dziulius

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.

dbackeus avatar Jul 20 '15 20:07 dbackeus