访问模块来自另一个类的配置常量

时间:2012-08-11 21:05:23

标签: ruby configuration gem require

我试图了解以下代码如何执行此操作:

attr_accessor *Configuration::VALID_CONFIG_KEYS

无需配置文件。以下是代码的一部分:

require 'openamplify/analysis/context'
require 'openamplify/connection'
require 'openamplify/request'

module OpenAmplify
  # Provides access to the OpenAmplify API http://portaltnx20.openamplify.com/AmplifyWeb_v20/
  #
  # Basic usage of the library is to call supported methods via the Client class.
  #
  #   text = "After getting the MX1000 laser mouse and the Z-5500 speakers i fell in love with logitech"
  #   OpenAmplify::Client.new.amplify(text)

  class Client
    include OpenAmplify::Connection
    include OpenAmplify::Request

    attr_accessor *Configuration::VALID_CONFIG_KEYS

    def initialize(options={})
      merged_options = OpenAmplify.options.merge(options)
      Configuration::VALID_CONFIG_KEYS.each do |key|
        send("#{key}=", merged_options[key])
      end
    end
  ....
  end

这是配置模块:

require 'openamplify/version'

# TODO: output_format, analysis, scoring can be specied in the client and becomes the default unless overriden

module OpenAmplify
  # Defines constants and methods for configuring a client
  module Configuration
    VALID_CONNECTION_KEYS = [:endpoint, :user_agent, :method, :adapter].freeze
    VALID_OPTIONS_KEYS    = [:api_key, :analysis, :output_format, :scoring].freeze

    VALID_CONFIG_KEYS     = VALID_CONNECTION_KEYS + VALID_OPTIONS_KEYS

    DEFAULT_ENDPOINT      = 'http://portaltnx20.openamplify.com/AmplifyWeb_v21/AmplifyThis'
    DEFAULT_HTTP_METHOD   = :get
    DEFAULT_HTTP_ADAPTER  = :net_http
    DEFAULT_USER_AGENT    = "OpenAmplify Ruby Gem #{OpenAmplify::VERSION}".freeze

    DEFAULT_API_KEY       = nil
    DEFAULT_ANALYSIS      = :all
    DEFAULT_OUTPUT_FORMAT = :xml
    DEFAULT_SCORING       = :standard
    DEFAULT_SOURCE_URL    = nil
    DEFAULT_INPUT_TEXT    = nil

    attr_accessor *VALID_CONFIG_KEYS
  ....
 end

这是来自此存储库:OpenAmplify

1 个答案:

答案 0 :(得分:1)

首先,在 configuration.rb client.rb 中,他们正在使用相同的命名空间,即模块OpenAmplify

尽管client.rb中不需要configuration.rb,但Ruby项目的约定通常要求在一个文件中包含所有必需的文件(通常与名称空间同名,并放在{ProjectName} / lib /中在这种情况下,文件是 openamplify / lib / openamplify.rb )。

因此,如果你去 openamplify / lib / openamplify.rb ,你会发现它实际上需要所有这两个文件:

require 'openamplify/configuration'
require 'openamplify/client'

由于常量已在 configuration.rb 中定义:

module OpenAmplify
  module Configuration
    VALID_CONFIG_KEYS = ...
  end
end

然后很明显,常量VALID_CONFIG_KEYS在Configuration :: VALID_CONFIG_KEYS的同一模块中显示(由 client.rb 重新打开)(前面的*只表示爆炸数组,因为VALID_CONFIG_KEYS是一个符号数组)

module OpenAmplify
  class Client
    attr_accessor *Configuration::VALID_CONFIG_KEYS
  end
end