我应该在 Sinatra(Ruby Web 框架)中的哪里放置我只想执行一次的代码?

发布于 2024-08-13 07:57:05 字数 428 浏览 3 评论 0原文

我不知道这是一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

挽手叙旧 2024-08-20 07:57:05
require 'rubygems'
require 'sinatra'

set :my_variable, "world"

get '/' do
  "Hello " + settings.my_variable
end
require 'rubygems'
require 'sinatra'

set :my_variable, "world"

get '/' do
  "Hello " + settings.my_variable
end
是你 2024-08-20 07:57:05

配置块仅与应用程序配置相关。如果是这样,您应该正确封装它:

require 'sinatra'

configure do
  set :my_option, "world"
end

get '/' do
  "Hello #{options.my_option}"
end

Configure block is just to app configuration related. If that's what it is, you should encapsulate it proper:

require 'sinatra'

configure do
  set :my_option, "world"
end

get '/' do
  "Hello #{options.my_option}"
end
無心 2024-08-20 07:57:05

另一种方法是:

require 'rubygems'
require 'sinatra'

@my_variable="world"

get '/' do
  "Hello " + @my_variable
end

One other way is :

require 'rubygems'
require 'sinatra'

@my_variable="world"

get '/' do
  "Hello " + @my_variable
end
旧情别恋 2024-08-20 07:57:05

我会设置一个类变量 - 例如。 @@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 of Sinatra::Base, so using a class variable in this situation seems appropriate.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文