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 #fetch, #store and #key?.

Instance Method Summary collapse

Instance Method Details

#get(key) ⇒ Object

Examples:

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

Parameters:

  • key (Symbol)


15
16
17
# File 'lib/clive/option/runner.rb', line 15

def get(key)
  @state.fetch key
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?



77
78
79
# File 'lib/clive/option/runner.rb', line 77

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

#set(key, value) ⇒ Object

Examples:

opt :set_some_key do
  set :some_key, 1
end

Parameters:

  • key (Symbol)
  • value (Object)


27
28
29
# File 'lib/clive/option/runner.rb', line 27

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)


53
54
55
56
57
58
59
60
61
62
63
# File 'lib/clive/option/runner.rb', line 53

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