Class: ChainOptions::Option

Inherits:
Object
  • Object
show all
Defined in:
lib/chain_options/option.rb

Overview

This class represents an Option from a ChainOptions::OptionSet and is mainly responsible for handling option state.

Constant Summary collapse

METHOD_SYMBOLS =

The Parameters that need to be turned into instance methods, if they are symbols.

%i[filter validate].freeze
PARAMETERS =
%i[incremental default transform filter validate invalid allow_block].freeze

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Option

Extracts options and sets all the parameters.



25
26
27
28
# File 'lib/chain_options/option.rb', line 25

def initialize(options)
  self.options = options
  @dirty = false
end

Instance Method Details

#allow_blockObject



18
19
20
# File 'lib/chain_options/option.rb', line 18

def allow_block
  options[:allow_block]
end

#current_valueObject

The current value if there is one. Otherwise returns the default value.



56
57
58
59
60
# File 'lib/chain_options/option.rb', line 56

def current_value
  return custom_value if dirty?

  default_value
end

#initial_value(value) ⇒ Object

Circumvents the normal value process to set an initial_value. Only works on a

clean option.

Raises:

  • (ArgumentError)


66
67
68
69
70
# File 'lib/chain_options/option.rb', line 66

def initial_value(value)
  raise ArgumentError, "The initial_value was already set to #{custom_value.inspect}." if dirty?

  self.custom_value = value
end

#new_value(*args, &block) ⇒ Object

Builds a new value for the option. It automatically applies transformations and filters and validates the resulting value, raising an exception if the value is not valid.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/chain_options/option.rb', line 35

def new_value(*args, &block)
  value = value_from_args(args, &block)

  value = if incremental
    incremental_value(value)
  else
    filter_value(transformed_value(value))
  end

  if value_valid?(value)
    self.custom_value = value
  elsif invalid.to_s == "default" && !incremental
    default_value
  else
    fail ArgumentError, "The value #{value.inspect} is not valid."
  end
end

#to_hObject

Looks through the parameters and returns the non-nil values as a hash



75
76
77
78
79
80
81
# File 'lib/chain_options/option.rb', line 75

def to_h
  PARAMETERS.each_with_object({}) do |param, hash|
    next if send(param).nil?

    hash[param] = send(param)
  end
end