Class: MVCLI::Form

Inherits:
Object
  • Object
show all
Includes:
Validatable
Defined in:
lib/mvcli/form.rb

Direct Known Subclasses

Plugins::InstallForm

Defined Under Namespace

Classes: Decoder, Input

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Validatable

included, #valid?, #validate!, #validation, #validators, #violations

Constructor Details

#initialize(params = {}, type = Map) ⇒ Form

Returns a new instance of Form.



21
22
23
24
# File 'lib/mvcli/form.rb', line 21

def initialize(params = {}, type = Map)
  @source = params
  @target = type
end

Class Attribute Details

.inputsObject (readonly)

Returns the value of attribute inputs.



57
58
59
# File 'lib/mvcli/form.rb', line 57

def inputs
  @inputs
end

.output(&block) ⇒ Object (readonly)

Returns the value of attribute output.



57
58
59
# File 'lib/mvcli/form.rb', line 57

def output
  @output
end

.targetObject

Returns the value of attribute target.



56
57
58
# File 'lib/mvcli/form.rb', line 56

def target
  @target
end

Class Method Details

.decoderObject



65
66
67
# File 'lib/mvcli/form.rb', line 65

def decoder
  Decoder.new self, inputs.keys
end

.inherited(base) ⇒ Object



59
60
61
62
63
# File 'lib/mvcli/form.rb', line 59

def inherited(base)
  base.class_eval do
    @inputs = Map.new
  end
end

.input(name, target, options = {}, &block) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/mvcli/form.rb', line 77

def input(name, target, options = {}, &block)
  if block_given?
    form = Class.new(MVCLI::Form, &block)
    form.target = [target].flatten.first
    validates_child name
    input = Input.new(name, target, options, &form.decoder)
  else
    input = Input.new(name, target, options, &options[:decode])
  end
  @inputs[name] = input
  if options[:required]
    if target.is_a?(Array)
      validates(name, "cannot be empty", nil: true, each: false) {|value| value && !value.empty?}
    else
      validates(name, "is required", nil: true) {|value| !value.nil?}
    end
  end
  define_method(name) do
    input.value @source, self
  end
end

Instance Method Details

#attributesObject



30
31
32
33
34
35
36
37
38
39
# File 'lib/mvcli/form.rb', line 30

def attributes
  self.class.inputs.reduce(Map.new) do |map, pair|
    name, input = *pair
    map.tap do
      map[name] = input.value(@source, self) do |value|
        value.is_a?(Form) ? value.attributes : value
      end
    end
  end
end

#valueObject



26
27
28
# File 'lib/mvcli/form.rb', line 26

def value
  self.class.output.call self
end