Module: Clive::StateActions

Included in:
Base, Command, Option::Runner
Defined in:
lib/clive/option/runner.rb

Overview

Methods for modifying a state object. Requires that the instance variable @state exists and that it responds to #[], #store and #key?.

Instance Method Summary collapse

Instance Method Details

#get(key) ⇒ Object

Gets the value for the key, returns nil if the key does not exist.

Examples:

set :some_key, 1
opt :get_some_key do
  puts get(:some_key)   #=> 1
end

Parameters:

  • key (Symbol)

17
18
19
# File 'lib/clive/option/runner.rb', line 17

def get(key)
  @state[key]
end

#get!(key) ⇒ Object

Gets the value for the key, raises an error if the key does not exist.

Parameters:

  • key (Symbol)

Raises:

  • (KeyError)

25
26
27
28
29
30
31
# File 'lib/clive/option/runner.rb', line 25

def get!(key)
  if has?(key)
    get(key)
  else
    raise KeyError, "key not found: #{key}"
  end
end

#has?(key) ⇒ Boolean

Returns State has key?.

Examples:

# test.rb
set :some_key, 1
opt(:has_some_key)  { puts has?(:some_key) }
opt(:has_other_key) { puts has?(:other_key) }

# ./test.rb --has-some-key   #=> true
# ./test.rb --has-other-key  #=> false

Parameters:

  • key (Symbol)

Returns:

  • (Boolean)

    State has key?


93
94
95
# File 'lib/clive/option/runner.rb', line 93

def has?(key)
  @state.key? key
end

#set(key, value) ⇒ Object

Sets the key to the value given.

Examples:

opt :set_some_key do
  set :some_key, 1
end

Parameters:

  • key (Symbol)
  • value (Object)

43
44
45
# File 'lib/clive/option/runner.rb', line 43

def set(key, value)
  @state.store key, value
end

#update(key, method, *args) ⇒ Object #update(key, &block) ⇒ Object

Overloads:

  • #update(key, method, *args) ⇒ Object

    Update the value for key using the method which is passed args

    Examples:

    set :list, []
    opt :add, arg: '<item>' do
      update :list, :<<, item
    end

    Parameters:

    • key (Symbol)
    • method (Symbol)
    • args (Object)
  • #update(key, &block) ⇒ Object

    Update the value for key with a block

    Examples:

    set :list, []
    opt :add, arg: '<item>' do
      update(:list) {|l| l << item }
    end

    Parameters:

    • key (Symbol)

69
70
71
72
73
74
75
76
77
78
79
# File 'lib/clive/option/runner.rb', line 69

def update(*args)
  if block_given?
    key = args.first
    set key, yield(get(key))
  elsif args.size > 1
    key, method = args.shift, args.shift
    set key, get(key).send(method, *args)
  else
    raise ArgumentError, "wrong number of arguments (#{args.size} for 2)"
  end
end