簡體   English   中英

在Ruby On Rails中初始化特定於寶石的變量信息

[英]Initializing Gem-Specific variables information in Ruby On Rails

我現在正在使用Rails 4.0應用程序(使用Ruby 2.0.0)。

我想在我的Rails應用程序的多個頁面中使用jenkins_api_client gem與Jenkins進行交互。

此gem通常使用@client參數,該參數初始化為包含Jenkins服務器的憑據和其他信息。 此參數使用如下所示初始化:

@client = JenkinsApi::Client.new(:server_ip => '0.0.0.0',
     :username => 'somename', :password => 'secret password')

初始化后,我想訪問此參數並在其上運行多個子例程。 這種初始化需要時間,我真的想避免每次客戶端之一想要使用此gem功能時都執行此過程,例如:

# Get a filtered list of jobs from the server
jobs_to_filter = "^test_job.*"
jobs = @client.job.list(jobs_to_filter)

因此,我希望只在Rails服務器啟動時執行一次。

我想在我的應用程序的多個頁面中使用此參數,可能會在以后使用線程化解決方案(此刻並不重要)。

誰能建議如何實現這一目標? 我希望得到與Rails約定一致的答案。

非常感謝!

例如,您可以創建類似這樣的內容:

module JenkinsApi
  class Client
    class << self
      attr_reader :instance, :config

      def configure(&block)
        @config = OpenStruct.new
        block.call @config
      end

      def instance
        @instance ||= JenkinsApi::Client.new @config
      end
    end
  end
end

它允許您在初始化程序中編寫:

JenkinsApi::Client.configure do |config|
  config.server_ip = '0.0.0.0'
  config.username = 'somename'
  config.password = 'secret password'
end

然后像這樣使用它: JenkinsApi::Client.instance.job.list(...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM