Class: MVCLI::Form

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

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.



8
9
10
11
# File 'lib/mvcli/form.rb', line 8

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

Class Attribute Details

.inputs ⇒ Object (readonly)

Returns the value of attribute inputs.



42
43
44
# File 'lib/mvcli/form.rb', line 42

def inputs
  @inputs
end

.output(&block) ⇒ Object (readonly)

Returns the value of attribute output.



42
43
44
# File 'lib/mvcli/form.rb', line 42

def output
  @output
end

.target ⇒ Object

Returns the value of attribute target.



41
42
43
# File 'lib/mvcli/form.rb', line 41

def target
  @target
end

Class Method Details

.decoder ⇒ Object



50
51
52
# File 'lib/mvcli/form.rb', line 50

def decoder
  Decoder.new self, inputs.keys
end

.inherited(base) ⇒ Object



44
45
46
47
48
# File 'lib/mvcli/form.rb', line 44

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

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



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/mvcli/form.rb', line 62

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) {|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

#attributes ⇒ Object



17
18
19
20
21
22
23
24
# File 'lib/mvcli/form.rb', line 17

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

#value ⇒ Object



13
14
15
# File 'lib/mvcli/form.rb', line 13

def value
  self.class.output.call self
end