Class: Mothership::Inputs

Inherits:
Object
  • Object
show all
Defined in:
lib/mothership/inputs.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(command, context = nil, inputs = {}) ⇒ Inputs

Returns a new instance of Inputs.



5
6
7
8
9
10
# File 'lib/mothership/inputs.rb', line 5

def initialize(command, context = nil, inputs = {})
  @command = command
  @context = context
  @inputs = inputs
  @cache = {}
end

Instance Attribute Details

#inputsObject (readonly)

Returns the value of attribute inputs.



3
4
5
# File 'lib/mothership/inputs.rb', line 3

def inputs
  @inputs
end

Instance Method Details

#[](name, *args) ⇒ Object



33
34
35
# File 'lib/mothership/inputs.rb', line 33

def [](name, *args)
  get(name, @context, *args)
end

#forget(name) ⇒ Object



86
87
88
89
# File 'lib/mothership/inputs.rb', line 86

def forget(name)
  @cache.delete(name)
  @inputs.delete(name)
end

#get(name, context, *args) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/mothership/inputs.rb', line 37

def get(name, context, *args)
  return @cache[name] if @cache.key? name

  meta = @command.inputs[name]
  return unless meta

  if @inputs.key?(name) && @inputs[name] != []
    val =
      if convert = meta[:from_given]
        if @inputs[name].is_a?(Array)
          @inputs[name].collect do |i|
            @context.instance_exec(i, *args, &convert)
          end
        else
          @context.instance_exec(@inputs[name], *args, &convert)
        end
      else
        @inputs[name]
      end

    return @cache[name] = val
  end

  val =
    if meta[:default].respond_to? :to_proc
      unless context
        raise "no context for input request"
      end

      context.instance_exec(*args, &meta[:default])
    elsif meta[:default]
      meta[:default]
    elsif meta[:type] == :boolean
      false
    elsif meta[:argument] == :splat
      if meta[:singular] && single = @inputs[meta[:singular]]
        [single]
      else
        []
      end
    end

  unless meta[:forget]
    @cache[name] = val
  end

  val
end

#given(name) ⇒ Object



16
17
18
# File 'lib/mothership/inputs.rb', line 16

def given(name)
  @inputs[name]
end

#given?(name) ⇒ Boolean

Returns:

  • (Boolean)


12
13
14
# File 'lib/mothership/inputs.rb', line 12

def given?(name)
  @inputs.key?(name)
end

#merge(inputs) ⇒ Object



20
21
22
# File 'lib/mothership/inputs.rb', line 20

def merge(inputs)
  self.class.new(@command, @context, @inputs.merge(inputs))
end

#without(*names) ⇒ Object



24
25
26
27
28
29
30
31
# File 'lib/mothership/inputs.rb', line 24

def without(*names)
  inputs = @inputs.dup
  names.each do |n|
    inputs.delete(n)
  end

  self.class.new(@command, @context, inputs)
end