gpt4 book ai didi

ruby-on-rails - Ruby 和 Sinatra 中全局变量的另一种方式

转载 作者:数据小太阳 更新时间:2023-10-29 07:47:37 24 4
gpt4 key购买 nike

我正在为我的应用程序使用 Ruby 和 Sinatra。

我想分配一个将在不同类和方法中使用的变量。

在我的应用程序文件中,即“Millennium”是我的应用程序名称,因此应用程序文件是 millennium.rb 包含:

require 'rubygems'
require 'sinatra'
require 'yaml'
require 'active_record'
require 'sidekiq'
require 'statsd'

custom_statsd = Statsd.new('localhost', 8125) #custom_statsd available across the application.

class Millennium < Sinatra::Application
set :use_queueing_in_dev, false # useful for debugging queue issues.
set :protection, :except => [:json_csrf]

configure do
# These allow our error handlers to capture the errors
disable :raise_errors
disable :show_exceptions
enable :logging
end

before do
#logger.info request.body.read
request.body.rewind
end
end

在这里,我想在我的应用程序的任何类中使用 custom_statsd 变量的值。

我认为使用“$”不是一个好主意。请建议我还有什么其他方法可以做到这一点。

谢谢!!!!

最佳答案

将实例放在共享配置模块中的类变量中可能稍微好一些,如下所示:

module MyAppConfig
def self.statsd
@statsd ||= Statsd.new('localhost', 8125)
end
end

class SomeOtherThing
def log!
MyAppConfig.statsd.something('hey')
end
end

SomeOtherThing.new.log!

关于ruby-on-rails - Ruby 和 Sinatra 中全局变量的另一种方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34989377/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com