Module: Gapic::Config

Included in:
Method
Defined in:
lib/gapic/config.rb,
lib/gapic/config/method.rb

Overview

Config is a simple DSL for creating Configuration classes.

Examples:

require "gapic/config"

class SampleConfig
  extend Gapic::Config

  config_attr :name,   nil,         String, nil
  config_attr :active, true,        true, false
  config_attr :count,  nil,         Numeric, nil
  config_attr :env,    :production, String, Symbol

  def initialize parent_config = nil
    @parent_config = parent_config unless parent_config.nil?
    yield self if block_given?
  end
end

config = SampleConfig.new

config.name             #=> nil
config.name = "thor"    #=> "thor"
config.name             #=> "thor"
config.name = :thor     # ArgumentError

Defined Under Namespace

Classes: Method

Instance Method Summary collapse

Instance Method Details

#config_attr(name, default, *valid_values, &validator) ⇒ Object

Add configuration attribute methods to the configuratin class.

Parameters:

  • name (String, Symbol)

    The name of the option

  • default (Object, nil)

    Initial value (nil is allowed)

  • valid_values (Array)

    A list of valid types

Raises:

  • (NameError)


51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/gapic/config.rb', line 51

def config_attr name, default, *valid_values, &validator
  name = String(name).to_sym
  name_setter = :"#{name}="
  raise NameError, "invalid config name #{name}" if name !~ /^[a-zA-Z]\w*$/ || name == :parent_config
  raise NameError, "method #{name} already exists" if method_defined? name
  raise NameError, "method #{name_setter} already exists" if method_defined? name_setter

  raise ArgumentError, "validation must be provided" if validator.nil? && valid_values.empty?
  validator ||= ->(value) { valid_values.any? { |v| v === value } }

  name_ivar = :"@#{name}"

  create_getter name_ivar, name, default
  create_setter name_ivar, name_setter, default, validator
end