class Radical::Form
Constants
- SELF_CLOSING_TAGS
Public Class Methods
new(options, controller)
click to toggle source
# 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
Public Instance Methods
close_tag()
click to toggle source
# File lib/radical/form.rb, line 76 def close_tag '</form>' end
csrf_tag()
click to toggle source
# File lib/radical/form.rb, line 66 def csrf_tag Rack::Csrf.tag(@controller.request.env) end
number(name, attrs = {})
click to toggle source
# 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_tag()
click to toggle source
# File lib/radical/form.rb, line 62 def open_tag "<form #{html_attributes(action: @action, method: @method)}>" end
rack_override_tag()
click to toggle source
# 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 = {})
click to toggle source
# 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 = {})
click to toggle source
# 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
Private Instance Methods
action_from(controller:, model:)
click to toggle source
# File lib/radical/form.rb, line 95 def action_from(controller:, model:) return if model.nil? route_name = controller.class.route_name if model.saved? controller.send(:"#{route_name}_path", model) else controller.send(:"#{route_name}_path") end end
html_attributes(options = {})
click to toggle source
# File lib/radical/form.rb, line 91 def html_attributes(options = {}) options.transform_keys(&:to_s).sort_by { |k, _| k }.map { |k, v| "#{k}=\"#{v}\"" }.join(' ') end
tag(name, attrs, &block)
click to toggle source
# File lib/radical/form.rb, line 82 def tag(name, attrs, &block) attr_string = attrs.empty? ? '' : " #{html_attributes(attrs)}" open_tag = "<#{name}" self_closing = SELF_CLOSING_TAGS.include?(name) end_tag = self_closing ? ' />' : "</#{name}>" "#{open_tag}#{attr_string}#{self_closing ? '' : '>'}#{block&.call}#{end_tag}" end