自定义类的初始化程序中的配置

时间:2014-02-09 23:37:21

标签: ruby-on-rails ruby

如何设置我正在编写的自定义gem的配置设置?

从其他宝石我看到配置文件看起来像这样:

# config/intializers/magento_client.rb
MagentoClient.configure do |config|
  config.consumer_key = "1234"
  config.consumer_secret = "5678"
  ...
end

我想在prepare_access_token方法中使用这些配置:

class MagentoClient
  require "oauth"
  require "omniauth"
  require "multi_json"
  require "ostruct"

  def initialize
    @access_token = prepare_access_token
  end

  def find_by(opts) 
    attributes = MultiJson.decode(@access_token.get("/api/rest/products?filter[1][attribute]=isbn&filter[1][eq]=#{opts[:isbn]}&filter[2][attribute]=purchase_type&filter[2][eq]=#{purchase_type_id}").body)
  end

private

  def prepare_access_token
    consumer = OAuth::Consumer.new(@@consumer_key, @@consumer_secret, {:site => @@url})
    token_hash = {oauth_token: @@access_key, oauth_token_secret: @@access_secret}
    access_token = OAuth::AccessToken.from_hash(consumer, token_hash)
  end
end

然后我想使用这样的类:

magento_client = MagentoClient.new
magento_client.find_by(isbn: 1234, purchase_type: "Buy New")

我可以使用与类相同的名称命名初始化程序文件(magento_client)吗?

3 个答案:

答案 0 :(得分:1)

一种简单的方法是在可配置类中使用一个基本配置对象作为类实例变量:

class MyClassConfiguration < Struct.new(:consumer_key, :consumer_secret)
end

class MyClass
  class << self
    def config
      @config ||= MyClassConfiguration.new
    end

    def configure(&block)
      yield config
    end
  end
end

MyClass.configure do |c|
  c.consumer_key = '1234'
  # etc ...
end

您还可以为MyClass的实例设置访问器以轻松读取配置对象,也可以使用Forwardable直接访问配置变量:

require 'forwardable'

class MyClass
  extend Forwardable

  def_delegators :config, :consumer_key, :consumer_secret

  def config
    self.class.config
  end
end

MyClass.new.consumer_key #=> '1234'
MyClass.new.consumer_secret #=> '5678'

答案 1 :(得分:1)

我会看一下关于开发引擎的ruby文档

http://guides.rubyonrails.org/engines.html

引擎提供了一种用于分配配置参数的简单架构。您可以将可配置元素定义为引擎定义的一部分。

您还可以查看具有广泛配置设置的Carrierwave等现有宝石。

https://github.com/carrierwaveuploader/carrierwave

答案 2 :(得分:0)

结束这个解决方案:

# in Gem: lib/magento_rest_api
require "magento_rest_api/version"

module MagentoRestApi
  class << self
    attr_accessor :consumer_key, :consumer_secret, :site, :access_key, :access_secret, :url_params
  end

  def self.configure(&block)
    yield self
  end  

  class Client
    require "oauth"

    def find_by(opts)
      @access_token ||= prepare_access_token       
      [...]   
    end
  private
    def prepare_access_token
      consumer = OAuth::Consumer.new(MagentoRestApi.consumer_key, MagentoRestApi.consumer_secret, :site => MagentoRestApi.site)
      token_hash = {oauth_token: MagentoRestApi.access_key, oauth_token_secret: MagentoRestApi.access_secret}
      access_token = OAuth::AccessToken.from_hash(consumer, token_hash)
    end
    [...]
  end
end

# in Rails: config/initializers/magento_rest_api.rb
MagentoRestApi.configure do |config|
  config.consumer_key = "123a"
  [...]
end