Class: Charming::Presentation::Components::Form::Field

Inherits:
Charming::Presentation::Component show all
Defined in:
lib/charming/presentation/components/form/field.rb

Direct Known Subclasses

Confirm, Input, Note, Select, Textarea

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from View

#focused?, #layout_assigns

Constructor Details

#initialize(name, label: nil, required: false, validate: nil, help: nil, theme: nil) ⇒ Field

Returns a new instance of Field.



10
11
12
13
14
15
16
17
# File 'lib/charming/presentation/components/form/field.rb', line 10

def initialize(name, label: nil, required: false, validate: nil, help: nil, theme: nil)
  super(theme: theme)
  @name = name.to_sym
  @label = label || humanize(name)
  @required = required
  @validator = validate
  @help = help
end

Instance Attribute Details

#helpObject (readonly)

Returns the value of attribute help.



8
9
10
# File 'lib/charming/presentation/components/form/field.rb', line 8

def help
  @help
end

#labelObject (readonly)

Returns the value of attribute label.



8
9
10
# File 'lib/charming/presentation/components/form/field.rb', line 8

def label
  @label
end

#nameObject (readonly)

Returns the value of attribute name.



8
9
10
# File 'lib/charming/presentation/components/form/field.rb', line 8

def name
  @name
end

#stateObject (readonly)

Returns the value of attribute state.



8
9
10
# File 'lib/charming/presentation/components/form/field.rb', line 8

def state
  @state
end

Instance Method Details

#bind(state) ⇒ Object



19
20
21
22
23
# File 'lib/charming/presentation/components/form/field.rb', line 19

def bind(state)
  @state = state
  state[:fields][name] ||= {}
  state[:values][name] = default_value unless state[:values].key?(name)
end

#focusable?Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/charming/presentation/components/form/field.rb', line 25

def focusable?
  true
end

#handle_key(_event) ⇒ Object



29
30
31
# File 'lib/charming/presentation/components/form/field.rb', line 29

def handle_key(_event)
  nil
end

#render(active: false) ⇒ Object



33
34
35
36
37
# File 'lib/charming/presentation/components/form/field.rb', line 33

def render(active: false)
  line = "#{active ? ">" : " "} #{render_control}"
  line = theme.selected.render(line) if active
  [line, help_line, *error_lines].compact.join("\n")
end

#validateObject



39
40
41
42
43
44
# File 'lib/charming/presentation/components/form/field.rb', line 39

def validate
  messages = []
  messages << "is required" if required? && blank?(value)
  messages.concat(validator_messages) if @validator
  messages
end

#valueObject



46
47
48
# File 'lib/charming/presentation/components/form/field.rb', line 46

def value
  state[:values][name]
end