Module: RailsStuff::Helpers::ResourceForm

Defined in:
lib/rails_stuff/helpers/resource_form.rb

Overview

Provides helper for SimpleForm.

Instance Method Summary collapse

Instance Method Details

#resource_form_for(namespace = nil, **options) ⇒ Object

Generates ‘resource_form` helper to display form with basic arguments, elements, errors and options. Generated method can work without arguments in most of cases: it takes object from `resource` method.

Use ‘namespace` to add additional path parts to form action:

# this one will use [:site, resource]
resource_form_for :site

#### Options

  • ‘back_url` - default back url. Can be string with code, or hash for `url_for`.

  • ‘resource_method` - method to take resource from.

  • ‘method` - name of generated method.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/rails_stuff/helpers/resource_form.rb', line 21

def resource_form_for(namespace = nil, **options)
  default_back_url =
    case options[:back_url]
    when Hash then "url_for(#{options[:back_url]})"
    when String then options[:back_url]
    else 'url_for(object)'
    end
  resource_method = options.fetch(:resource_method, :resource)
  method_name = options.fetch(:method, :resource_form)
  object_arg = (Array.wrap(namespace).map(&:inspect) + [resource_method]).join(', ')

  class_eval "    def \#{method_name}(object = [\#{object_arg}], **options)\n      back_url = options.delete(:back_url) || \#{default_back_url}\n      simple_form_for object, options do |f|\n        html = ActiveSupport::SafeBuffer.new\n        msg = f.object.errors[:base].first\n        html << content_tag(:div, msg, class: 'alert alert-danger') if msg\n        html << capture { yield(f) }\n        html << f.button(:submit, class: 'btn-primary')\n        html << ' '\n        html << link_to(translate_action(:cancel), back_url, class: :btn)\n      end\n    end\n  RUBY\nend\n", __FILE__, __LINE__ + 1