Sha256: 17e390a976d40b15376bb69c18f2d3aaeb078941c9abbfdc28447cd5493e0809

Contents?: true

Size: 1.84 KB

Versions: 6

Compression:

Stored size: 1.84 KB

Contents

module Trestle
  class Form
    class Renderer
      include ::ActionView::Context
      include ::ActionView::Helpers::CaptureHelper

      # Whitelisted helpers will concatenate their result to the output buffer when called.
      WHITELISTED_HELPERS = [:row, :col, :render, :tab, :toolbar, :table, :divider]

      # Raw block helpers will pass their block argument directly to the method
      # without wrapping it in a new output buffer.
      RAW_BLOCK_HELPERS = [:table]

      # The #select and #display methods are defined on Kernel. Undefine them so
      # that they can be delegated to the form builder or template by method_missing.
      undef_method :select, :display

      delegate :concat, to: :output_buffer

      def initialize(template, form=nil)
        @template = template
        @form = form || @template.form
      end

      def render_form(*args, &block)
        capture { instance_exec(*args, &block).to_s }
      end

      def fields_for(*args, &block)
        result = @form.fields_for(*args) do |f|
          renderer = self.class.new(@template, f)
          renderer.render_form(f, &block)
        end

        concat(result)
      end

      def method_missing(name, *args, &block)
        target = @form.respond_to?(name) ? @form : @template

        if block_given? && !RAW_BLOCK_HELPERS.include?(name)
          result = target.send(name, *args) do |*blockargs|
            render_form(*blockargs, &block)
          end
        else
          result = target.send(name, *args, &block)
        end

        if target == @form || WHITELISTED_HELPERS.include?(name)
          concat(result)
        else
          result
        end
      end

      def respond_to_missing?(name, include_all=false)
        @form.respond_to?(name, include_all) ||
          @template.respond_to?(name, include_all) ||
          super
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
trestle-0.8.6 lib/trestle/form/renderer.rb
trestle-0.8.5 lib/trestle/form/renderer.rb
trestle-0.8.4 lib/trestle/form/renderer.rb
trestle-0.8.3 lib/trestle/form/renderer.rb
trestle-0.8.2 lib/trestle/form/renderer.rb
trestle-0.8.0 lib/trestle/form/renderer.rb