0

我试图了解以下代码如何做到这一点:

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

4

1 回答 1

1

首先,在configuration.rbclient.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 在同一模块中(由 client.rb 重新打开通过 Configuration::VALID_CONFIG_KEYS 可见(并且前面的 * 仅表示爆炸数组,因为 VALID_CONFIG_KEYS 是符号数组)

module OpenAmplify
  class Client
    attr_accessor *Configuration::VALID_CONFIG_KEYS
  end
end
于 2012-08-12T17:24:18.563 回答