Sinatra 服务器运行后执行代码 [英] Execute code once Sinatra server is running

查看:42
本文介绍了Sinatra 服务器运行后执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含在 Sinatra::Base 中的 Sinatra 应用程序,我想在服务器启动后运行一些代码,我应该怎么做?

I have a Sinatra Application enclosed in Sinatra::Base and I'd like to run some code once the server has started, how should I go about doing this?

这是一个例子:

require 'sinatra'
require 'launchy'

class MyServer < Sinatra::Base
  get '/' do
    "My server"
  end

  # This is the bit I'm not sure how to do
  after_server_running do
    # Launches a browser with this webapp in it upon server start
    Launchy.open("http://#{settings.host}:#{settings.port}/")
  end
end

有什么想法吗?

推荐答案

使用 configure 块不是执行此操作的正确方法.每当您加载文件时,都会运行命令.

Using the configure block is not the correct way to do this. Whenever you load the file the commands will be run.

尝试扩展 run!

require 'sinatra'
require 'launchy'

class MyServer < Sinatra::Base

  def self.run!
    Launchy.open("http://#{settings.host}:#{settings.port}/")
    super
  end

  get '/' do
    "My server"
  end
end

这篇关于Sinatra 服务器运行后执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆