2013-08-16 2 views
0

레일 3에 존재하는 number_field 폼 헬퍼를 레일 2.3.15 어플리케이션에 추가하고 싶지만 모듈을 확장하는 데 문제가 있습니다. 레일 추가하기 3 폼 헬퍼를 레일에 추가하기 2

내가 내가 내 응용 프로그램 도우미에 포함 모듈이를 추가 해요 레일 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 모듈 방법 나는 조상 체인을 알아 내지 못하고 범위를 지정하는 방법을 모르므로 문제가 있습니다. 기본적으로 작동시키는 법을 모르겠습니다.

답변

0

위의 문제점은 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'

를 생성합니다 어떤 사용자 지정 양식 빌더가있는 경우/확장뿐만 아니라 것을 오버라이드 (override) 할 필요가 있습니다. 네임 스페이스는 다를 수 있지만 대부분 표준은 다음과 같습니다.

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