Sha256: 0cc5072282dafa9d4df91be26ff18ac0b742d1eb4fcbbef9251d18cf329f57fd

Contents?: true

Size: 1.38 KB

Versions: 10

Compression:

Stored size: 1.38 KB

Contents

module Trestle
  class Form
    class Builder < ActionView::Helpers::FormBuilder
      # The #display method is defined on Kernel. Undefine it so that the
      # Builder instance will not respond_to?(:display) allowing the method to
      # be dispatched to the template helpers instead.
      undef_method :display

      cattr_accessor :fields
      self.fields = {}

      def errors(name)
        if object.respond_to?(:errors) && object.errors.respond_to?(:[])
          object.errors[name].to_a
        else
          []
        end
      end

      def self.register(name, klass)
        rename_existing_helper_method(name)
        self.fields[name] = klass
      end

    protected
      def respond_to_missing?(name, include_all=false)
        self.class.fields.has_key?(name) || super
      end

      def method_missing(name, *args, &block)
        if field = self.class.fields[name]
          field.new(self, @template, *args, &block).render
        else
          super
        end
      end

      def self.rename_existing_helper_method(name)
        # Check if a method exists with the given name
        return unless method_defined?(name)

        # Prevent a method from being aliased twice
        return if method_defined?(:"raw_#{name}")

        alias_method :"raw_#{name}", name
        undef_method name
      end
    end
  end
end

# Load all form fields
Trestle::Form::Fields.eager_load!

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
trestle-0.9.2 lib/trestle/form/builder.rb
trestle-0.9.1 lib/trestle/form/builder.rb
trestle-0.9.0 lib/trestle/form/builder.rb
trestle-0.8.13 lib/trestle/form/builder.rb
trestle-0.8.12 lib/trestle/form/builder.rb
trestle-0.8.11 lib/trestle/form/builder.rb
trestle-0.8.10 lib/trestle/form/builder.rb
trestle-0.8.9 lib/trestle/form/builder.rb
trestle-0.8.8 lib/trestle/form/builder.rb
trestle-0.8.7 lib/trestle/form/builder.rb