加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 01:35:58 所属栏目:百科 来源:网络整理
导读:我正在使用 Ruby和Sinatra作为我的应用程序. 我想分配一个将在不同的类和方法中使用的变量. 在我的应用程序文件中,即’Millennium’是我的应用程序名称,因此应用程序文件是millennium.rb包含: require 'rubygems'require 'sinatra'require 'yaml'require 'a
我正在使用 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!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读