Class: Clive::Option::Runner

Inherits:
Object
  • Object
show all
Extended by:
StateActions
Defined in:
lib/clive/option/runner.rb

Overview

Runner is a class which is used for executing blocks given to Options and Commands. It allows you to inside blocks;

  • reference arguments by name (instead of using block params)

  • get values from the state hash

  • set value to the state hash

  • update values in the state hash

Examples:

Referencing Arguments by Name


opt :size, args: '<height> <width>', as: [Float, Float] do # no params!
  puts "Area = #{height} * #{width} = #{height * width}"
end

Getting Values from State


command :new, arg: '<dir>' do

  opt :type, in: %w(post page blog)

  action do
    type = has?(:type) ? get(:type) : 'page'
    puts "Creating #{type} in #{dir}!"
  end

end

Setting Values to State


opt :set, arg: '<key> <value>', as: [Symbol, Object] do
  set key, value
end

Updating Values in State


opt :modify, arg: '<key> <sym> [<args>]', as: [Symbol, Symbol, Array] do
  update key, sym, *args
end

Class Method Summary collapse

Methods included from StateActions

get, get!, has?, set, update

Class Method Details

._run(args, state, fn) ⇒ Object

Parameters:

  • args (Array[Symbol,Object])

    An array is used because with 1.8.7 a hash has unpredictable ordering of keys, this means an array is the only way I can be sure that the arguments are in order.

  • state (Hash{Symbol=>Object})
  • fn (Proc)

149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/clive/option/runner.rb', line 149

def _run(args, state, fn)
  return unless fn
  # order of this doesn't matter as it will just be accessed by key
  @args = Hash[args]
  @state = state

  if fn.arity > 0
    # Remember to use the ordered array version
    instance_exec(*args.map {|i| i.last }, &fn)
  else
    instance_exec(&fn)
  end

  @state
end

.method_missing(sym, *args) ⇒ Object

Allows arguments passed in to be referenced directly by name.


168
169
170
171
172
173
174
# File 'lib/clive/option/runner.rb', line 168

def method_missing(sym, *args)
  if @args.has_key?(sym)
    @args[sym]
  else
    super
  end
end