Module: Harbor::ViewContext::Helpers::Form

Included in:
Harbor::ViewContext
Defined in:
lib/harbor/view_context/helpers/form.rb

Instance Method Summary collapse

Instance Method Details

#form(action, options = {}, &block) ⇒ Object

Form helper which abstracts away setting necessary information:

1. If no enctype is passed, and a file input is found, uses
   multipart/form-data.
2. Creates a hidden input for setting _method when method option
   is put or delete.


10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/harbor/view_context/helpers/form.rb', line 10

def form(action, options = {}, &block)
  method = options.delete(:method) || :post

  get = method == :get
  post = method == :post

  body = capture(&block)

  enctype = options.delete(:enctype) || (body =~ /\<input[^>]+?type\=["']file["']/ ? "multipart/form-data" : nil)

  with_buffer(block) do |buffer|
    buffer << "<form action=\"#{action}\" method=\"#{get ? "get" : "post"}\""
    buffer << " enctype=\"#{enctype}\"" if enctype
    buffer << " #{options.map { |k, v| "#{k}=\"#{v}\"" }.join(" ")}" unless options.empty?
    buffer << ">\n"

    unless get || post
      buffer << "  <input type=\"hidden\" name=\"_method\" value=\"#{method}\">\n"
    end

    buffer << body
    buffer << "</form>\n"
  end
end