簡體   English   中英

將rails 3表單助手添加到rails 2

[英]Adding rails 3 form helpers to rails 2

我想將Rails 3中存在的number_field表單助手添加到我的rails 2.3.15應用程序中,但是我在擴展模塊時遇到了麻煩。

這些是我從Rails 3需要的方法

class InstanceTag
    def to_number_field_tag(field_type, options = {})
        options = options.stringify_keys
        if range = options.delete("in") || options.delete("within")
          options.update("min" => range.min, "max" => range.max)
        end
        to_input_field_tag(field_type, options)
      end
end

def number_field(object_name, method, options = {})
        InstanceTag.new(object_name, method, self, options.delete(:object)).to_number_field_tag("number", options)
end

def number_field_tag(name, value = nil, options = {})
        options = options.stringify_keys
        options["type"] ||= "number"
        if range = options.delete("in") || options.delete("within")
          options.update("min" => range.min, "max" => range.max)
        end
        text_field_tag(name, value, options)
end

我將其添加到我的應用程序幫助程序中包含的模塊中。 to_number_field_tag方法很簡單,因為我可以打開類並添加覆蓋。

我遇到麻煩的FormHelper模塊方法,因為我不太清楚祖先鏈,也不知道如何確定覆蓋范圍。 我不知道該如何使其基本工作。

我上面的問題是我沒有重寫FormBuilder。 這是針對將來可能需要此解決方案的人的解決方案。

我決定不只是實現type="number"輸入類型,而是決定為所有新的HTML5輸入創建通用幫助器。 我將此代碼放在我包含在application_helper.rb中的替代文件中。

# file 'rails_overrides.rb`

ActionView::Helpers::InstanceTag.class_eval do
    def to_custom_field_tag(field_type, options = {})
        options = options.stringify_keys
        to_input_field_tag(field_type, options)
      end
end

ActionView::Helpers::FormBuilder.class_eval do
    def custom_field(method, options = {}, html_options = {})
        @template.custom_field(@object_name, method, objectify_options(options), html_options)
    end
end

# form.custom_field helper to use in views
def custom_field(object_name, method, options = {}, html_options = {})
    ActionView::Helpers::InstanceTag.new(object_name, method, self, options.delete(:object)).to_custom_field_tag(options.delete(:type), options)
end

# form.custom_field_tag helper to use in views
def custom_field_tag(name, value = nil, options = {})
    options = options.stringify_keys
    # potential sanitation. Taken from rails3 code for number_field
    if range = options.delete("in") || options.delete("within")
      options.update("min" => range.min, "max" => range.max)
    end
    text_field_tag(name, value, options)
end

然后在您的視圖中使用它:

<% form_for... do |form| %>
    <%= form.custom_field :user_age, :type=>"number", :min=>"0", :max=>"1000" %>
    <%= form.custom_field :email, :type=>"email", :required=>"true" %>
<% end %>

這將生成一個<input type='number', and an <input type='email'

如果您有一個自定義表單構建器,則還需要擴展/覆蓋它。 命名空間可能有所不同,但大多數標准是這樣的:

MySpecialFormBuilder.class_eval do
    def custom_field(method, options = {}, html_options = {})
        ...custom form builder implementation
    end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM