ruby / sinatra:路由外部的代码仅会运行一次还是每次ping通?

时间:2019-05-04 18:48:42

标签: ruby sinatra

我有一个苗条的Sinatra网站。

如果我在get路由之外包含代码,它将仅在后台运行一次,还是在每次ping IP地址时触发。

例如,功能“启动” 仅在创建服务器/ gitpush时运行一次,还是在每次访问站点时重新运行。

-

other-code.rb

$variable
$count = 0
def start
  $variable = "hello world + #{$count}"
  $count += 1
end

start

-

index.rb

require 'sinatra'
require 'json'
require 'other-code'

get '/' do

content_type :json
    puts $variable

end

1 个答案:

答案 0 :(得分:2)

Require仅从所需文件中加载一次ruby代码。 这是您可以知道的方法:

#index.rb

require 'sinatra'
require 'json'
require_relative 'other_code'

get '/' do
  content_type :json
  puts $variable
end


# other_code.rb

$variable

def start
  $variable = 'hello world'
end
puts 'other code called'
start

现在启动您的sinatra服务器

ruby index.rb

您将在控制台中看到它:

other code called
== Sinatra (v2.0.5) has taken the stage on 4567 for development with backup from Puma
Puma starting in single mode...

然后几次点击浏览器并查看控制台,您只会看到other code called输出1次。但是,每次您到达获取路线时,您都应该看到输出hello world!