Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sinatra pass variables to erb

Tags:

ruby

sinatra

There's two ways I can do this.

First is to use :locals => {....} and other is to use @var_name. I am just wondering which one is better/preferred? I couldn't find the answer to this anywhere.

Thanks

like image 848
0xSina Avatar asked Dec 23 '12 18:12

0xSina


1 Answers

I have no experience but probably you write less code using @var_name, but if let's say you have 2 actions which render the same view with different objects let's say one with foo and the other with bar, you probably would want to use locals.

def foos
  foos = Foo.all
  erb :something, locals: {list: foos} 
end

def foos
  bars = Foo.all
  erb :something, locals: {list: bars} 
end

Instead of @vars, wich you have to use the same var_name that does not truly represent what's inside. Like: It's a list of what??

def bars
  @list = Bar.all
  erb :something
end

def foos
  @list = Foo.all
  erb :something 
end

Or maybe you should be good with @vars, because most of the time you reuse a view when you render the same kind of objects like:

def foos
  @foos = Foo.all
  erb :something
end

def bar_foos
  @foos = Foo.where(bar: true)
  erb :something 
end

So you probably just want to use locals when rendering partials wich most of the time are used in different contexts. Like a form when you render for a @new_bar, and and existing @bar. Just an example. Or for example a @current_user or a simple @user

like image 79
Ismael Avatar answered Sep 29 '22 19:09

Ismael