Sinatra Variable Scope

北城余情 提交于 2019-12-04 02:40:20
Marc Seeger

Might not be the "cleanest" way to do it, but setting them as options should work:
--> http://www.sinatrarb.com/configuration.html :)

setting:

set :foo, 'bar'

getting:

"foo is set to " + settings.foo

Make them constants. They should be anyway shouldn't they? They're not going to change.

Make a constant by writing it in all caps.

Read this article on Ruby Variable Scopes if you have any more issues. http://www.techotopia.com/index.php/Ruby_Variable_Scope

Another clean option may be a config class, where the init method loads the YAML and then sets up the variables.

Have fun. @reply me when you've finished your new blog (I'm guessing this is what this is for).

From the Sinatra README:


Accessing Variables in Templates

Templates are evaluated within the same context as route handlers. Instance variables set in route handlers are direcly accessible by templates:

get '/:id' do
  @foo = Foo.find(params[:id])
   haml '%h1= @foo.name'
end

Or, specify an explicit Hash of local variables:

get '/:id' do
  foo = Foo.find(params[:id])
  haml '%h1= foo.name', :locals => { :foo => foo }
end

This is typically used when rendering templates as partials from within other templates.


A third option would be to set up accessors for them as helper methods. (Which are also available throughout the application and views.)

what also works:

@@foo = "bar"

But don't forget to restart the server after this change

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!