Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
dbackeus opened this issue Jul 20, 2015 · 4 comments
Open

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

dbackeus opened this issue Jul 20, 2015 · 4 comments

Comments

@dbackeus
Copy link

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
Copy link
Contributor

@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
Copy link
Author

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
Copy link

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

@dbackeus
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants