开发者

Custom Form Elements in Rails

开发者 https://www.devze.com 2022-12-19 12:04 出处:网络
So I\'m new to Rails and I\'m trying to figure out what the canonical way to add custom form elements is. Currently the way I\'m doing it is super grotty.

So I'm new to Rails and I'm trying to figure out what the canonical way to add custom form elements is. Currently the way I'm doing it is super grotty.

module ActionView
  module Helpers
    module FormOptionsHelper
      def some_new_field(object, method, options = {}, html_options = {})
          #code code
      end
    end
    class FormBuilder 
      def contract_year_select(method, options = {}, html_options = {})
        @template.some_new_field(@object_name, method, objectify_op开发者_如何学Pythontions(options), @default_options.merge(html_options))
      end
    end
  end
end

I have seen this however.

class Forms::ApplicationFormBuilder < ActionView::Helpers::FormBuilder
  Forms::ApplicationHelper.instance_methods.each do |selector|
    src = <<-end_src
      def #{selector}(method, options = {})
        @template.send(#{selector.inspect}, @object_name, method, objectify_options(options))
      end
    end_src
    class_eval src, __FILE__, __LINE__
  end

  private

  def objectify_options(options)
    @default_options.merge(options.merge(:object => @object))
  end
end

(from here)

Extending FormBuilder seems like a better solution than duck punching it. Is there some other way to do this that doesn't require directly copying parts of the FormBuilder class into my custom one?


Two parter here:

First, as someone new to rails, I would recommend using the Formtastic gem. V is the abused and neglected part of MVC in rails.

Formtastic is very well tested and has support for Rails 3

https://github.com/justinfrench/formtastic

With Formtastic you can then create custom elements extending it's brilliant class and get a whole host of other benefits beyond simple field display.

Second, extending the class is definitely acceptable. I prefer the Module method as it's easier to look at. Like something along the lines of:

module Forms::ApplicationFormBuilder
 class WhateverYourExtending
  def some_special_method(stuff)
   # all kinds of special stuff here
  end
 end
end

But I barely know what I am talking about here... This stuff is right on the edge of my understanding.

Just saw you talking about forms and I love Formtastic!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号