简体   繁体   English

在Ruby On Rails中初始化特定于宝石的变量信息

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

I am working right now on a Rails 4.0 application (using Ruby 2.0.0). 我现在正在使用Rails 4.0应用程序(使用Ruby 2.0.0)。

I would like to interact with Jenkins using jenkins_api_client gem, from multiple pages of my Rails application . 我想在我的Rails应用程序的多个页面中使用jenkins_api_client gem与Jenkins进行交互。

This gem generally using a @client parameter, which is initialized to contain the credentials and other information of the Jenkins server. 此gem通常使用@client参数,该参数初始化为包含Jenkins服务器的凭据和其他信息。 This parameter in initialized using something like this: 此参数使用如下所示初始化:

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

Once initialized, I would like to access this parameter and run multiple sub-routines on it. 初始化后,我想访问此参数并在其上运行多个子例程。 This initialization takes time, and I really want to avoid doing this process every time one of the clients would like to use this gem functionality, such as: 这种初始化需要时间,我真的想避免每次客户端之一想要使用此gem功能时都执行此过程,例如:

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

So, I hope to do this only once- when the rails server starts. 因此,我希望只在Rails服务器启动时执行一次。

I would like to use this parameter from multiple pages of my app, possibly with threaded solution further down the road (not critical at the moment). 我想在我的应用程序的多个页面中使用此参数,可能会在以后使用线程化解决方案(此刻并不重要)。

Can anyone recommend how to achieve this? 谁能建议如何实现这一目标? I'd appreciate an answer which is consistent with Rails convention. 我希望得到与Rails约定一致的答案。

Thanks a lot! 非常感谢!

as example you could create something like that: 例如,您可以创建类似这样的内容:

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

which allow you write in initializer: 它允许您在初始化程序中编写:

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

and then use it like: JenkinsApi::Client.instance.job.list(... 然后像这样使用它: JenkinsApi::Client.instance.job.list(...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM