amethyst-framework / amethyst

Amethyst is a Rails inspired web-framework for Crystal language
https://github.com/amethyst-framework
MIT License
648 stars 46 forks source link

Can't use an array as a view variable #37

Open dbackeus opened 8 years ago

dbackeus commented 8 years ago

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?

bararchy commented 8 years ago

@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

dbackeus commented 8 years ago

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.

dziulius commented 8 years ago

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

dbackeus commented 8 years ago

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.