Class: Radical::Form

Inherits:
Object
  • Object
show all
Defined in:
lib/radical/form.rb

Constant Summary collapse

SELF_CLOSING_TAGS =
%w[
  area
  base
  br
  col
  embed
  hr
  img
  input
  keygen
  link
  meta
  param
  source
  track
  wbr
].freeze

Instance Method Summary collapse

Constructor Details

#initialize(options, controller) ⇒ Form

Returns a new instance of Form.



25
26
27
28
29
30
31
# File 'lib/radical/form.rb', line 25

def initialize(options, controller)
  @model = options[:model]
  @controller = controller
  @override_method = options[:method]&.upcase || (@model&.saved? ? 'PATCH' : 'POST')
  @method = %w[GET POST].include?(@override_method) ? @override_method : 'POST'
  @action = options[:action] || action_from(model: @model, controller: controller)
end

Instance Method Details

#button(attrs = {}, &block) ⇒ Object



45
46
47
# File 'lib/radical/form.rb', line 45

def button(attrs = {}, &block)
  tag 'button', attrs, &block
end

#close_tagObject



76
77
78
# File 'lib/radical/form.rb', line 76

def close_tag
  '</form>'
end

#csrf_tagObject



66
67
68
# File 'lib/radical/form.rb', line 66

def csrf_tag
  Rack::Csrf.tag(@controller.request.env)
end

#number(name, attrs = {}) ⇒ Object



39
40
41
42
43
# File 'lib/radical/form.rb', line 39

def number(name, attrs = {})
  attrs.merge!(type: 'number', name: name, value: @model&.public_send(name))

  tag 'input', attrs
end

#open_tagObject



62
63
64
# File 'lib/radical/form.rb', line 62

def open_tag
  "<form #{html_attributes(action: @action, method: @method)}>"
end

#rack_override_tagObject



70
71
72
73
74
# File 'lib/radical/form.rb', line 70

def rack_override_tag
  attrs = { value: @override_method, type: 'hidden', name: '_method' }

  tag('input', attrs) unless %w[GET POST].include?(@override_method)
end

#submit(value_or_attrs = {}) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/radical/form.rb', line 49

def submit(value_or_attrs = {})
  attrs = {}

  case value_or_attrs
  when String
    attrs[:value] = value_or_attrs
  when Hash
    attrs = value_or_attrs || {}
  end

  tag 'input', attrs.merge('type' => 'submit')
end

#text(name, attrs = {}) ⇒ Object



33
34
35
36
37
# File 'lib/radical/form.rb', line 33

def text(name, attrs = {})
  attrs.merge!(type: 'text', name: name, value: @model&.public_send(name))

  tag 'input', attrs
end