Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Another way for global variable in Ruby and Sinatra

I am using Ruby and Sinatra for my application.

I want to assign a variable which will be used in different classes and methods.

In my app file ie 'Millennium' is my app name so the application file is millennium.rb contains :

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

Here I want to use value of custom_statsd variable in any class of my application.

I think using "$" is not a good idea. Please suggest me what is the other way to do this.

Thanks!!!!

like image 219
joe Avatar asked Apr 09 '26 10:04

joe


2 Answers

It might be marginally better to put the instance in a class variable in a shared config module, like so:

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!
like image 200
Jesper Avatar answered Apr 10 '26 23:04

Jesper


Using a global variable in general is not recommended but in certain circumstances it is the simplest so the best way, just don't overuse it. I recommend using a single constant as a namespace here, initialised from a yaml config file.

CONFIG = YAML::load_file("./config.yaml")

to_monitor CONFIG.monitor.osign_job_id

here the config.yaml

--- !ruby/struct
  zf: 999
  debug_level: DEBUG # available log levels are: DEBUG, INFO, WARN, ERROR and  FATAL 
  :monitor: !ruby/struct
    osign_job_id: 86
like image 41
peter Avatar answered Apr 11 '26 00:04

peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!