File: forms.rb

package info (click to toggle)
ruby-arbre 1.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid
  • size: 440 kB
  • sloc: ruby: 1,716; makefile: 7
file content (96 lines) | stat: -rw-r--r-- 2,202 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# frozen_string_literal: true
module Arbre
  module Rails
    module Forms

      class FormBuilderProxy < Arbre::Component
        attr_reader :form_builder

        # Since label and select are Arbre Elements already, we must
        # override it here instead of letting method_missing
        # deal with it
        def label(*args)
          proxy_call_to_form :label, *args
        end

        def select(*args)
          proxy_call_to_form :select, *args
        end

        def respond_to_missing?(method, include_all)
          if form_builder && form_builder.respond_to?(method, include_all)
            true
          else
            super
          end
        end

        private

        def proxy_call_to_form(method, *args, &block)
          text_node form_builder.send(method, *args, &block)
        end

        ruby2_keywords def method_missing(method, *args, &block)
          if form_builder && form_builder.respond_to?(method)
            proxy_call_to_form(method, *args, &block)
          else
            super
          end
        end

      end

      class FormForProxy < FormBuilderProxy
        builder_method :form_for

        def build(resource, form_options = {}, &block)
          form_string = helpers.form_for(resource, form_options) do |f|
            @form_builder = f
          end

          @opening_tag, @closing_tag = split_string_on(form_string, "</form>")
          super(&block)
        end

        def fields_for(*args, &block)
          insert_tag FieldsForProxy, form_builder, *args, &block
        end

        def split_string_on(string, match)
          return "" unless string && match
          part_1 = string.split(Regexp.new("#{match}\\z")).first
          [part_1, match]
        end

        def opening_tag
          @opening_tag || ""
        end

        def closing_tag
          @closing_tag || ""
        end

      end

      class FieldsForProxy < FormBuilderProxy

        def build(form_builder, *args, &block)
          form_builder.fields_for(*args) do |f|
            @form_builder = f
          end

          super(&block)
        end

        def to_s
          children.to_s
        end

      end

    end
  end
end