我应该在 Sinatra(Ruby Web 框架)中的哪里放置我只想执行一次的代码?
我不知道这是一个 ruby 问题还是一个 Sinatra 问题,因为我对这两个问题都是新手。下面的代码不起作用,我明白为什么,因为第一个 my_variable 是其块的本地变量。我只是不知道正确的语法。
require 'rubygems'
require 'sinatra'
configure do
my_variable = "world"
end
get '/' do
"Hello " + my_variable
end
编辑1 - 以下有效,但我想我对配置块的正确用途感到困惑。
require 'rubygems'
require 'sinatra'
my_variable = "world"
get '/' do
"Hello " + my_variable
end
I don't know if this is a ruby question or a Sinatra question, because I'm new to both. The following code does not work, and I understand why, because the first my_variable is local to its block. I just don't know the syntax for getting it right.
require 'rubygems'
require 'sinatra'
configure do
my_variable = "world"
end
get '/' do
"Hello " + my_variable
end
EDIT1 - the following works, but then I guess I'm confused about the proper purpose of the configure block.
require 'rubygems'
require 'sinatra'
my_variable = "world"
get '/' do
"Hello " + my_variable
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
配置块仅与应用程序配置相关。如果是这样,您应该正确封装它:
Configure block is just to app configuration related. If that's what it is, you should encapsulate it proper:
另一种方法是:
One other way is :
我会设置一个类变量 - 例如。
@@my_variable
— 在配置块内。配置块适用于您想要在启动时运行的代码,因此设置变量是有意义的。您的 Sinatra 应用程序是Sinatra::Base
的子类,因此在这种情况下使用类变量似乎是合适的。I would set a class variable — eg.
@@my_variable
— inside the configure block. The configure block exists for code you want to run at start up, so setting your variable their makes sense. Your Sinatra application is a subclass ofSinatra::Base
, so using a class variable in this situation seems appropriate.