2016-12-07 5 views
1

new.html.erbのRails:理解カスタムフォームヘルパー

<%= form_for @star do |f|%> 
    <%= star_radio(f, true)%> 
<% end %> 

stars_helper.rb

module StarHelper 
    def star_radio(form, status) 
    form.label "star_#{status}", class: 'radio-inline' do 
     form.radio_button(:star, status) + i18n_star(status) 
    end 
    end 

    def i18n_star (status) 
    I18n.t("activerecord.attributes.star.is_sun.#{status}") 
    end 
end 

私は、上記のようなコードの一部を見ました。
私はカスタムフォームヘルパーに慣れていません。
ブロック内にform.radio_button(:star, status) + i18n_star(status)を使用する理由と、ラジオボタンにテキストを追加するために「+」を使用できる理由を教えてください。
私がこれを学ぶためにどこに行くことができるか教えていただければ幸いです。

答えて

1

ヘルパーは文字列を返し、I18n.tも文字列を返します。したがって、それらを連結することができます。実装で

https://github.com/casunlight/rails/blob/master/actionview/lib/action_view/helpers/form_helper.rb

def radio_button(object_name, method, tag_value, options = {}) 
    Tags::RadioButton.new(object_name, method, self, tag_value, options).render 
end 

ルックrenderメソッド

https://github.com/casunlight/rails/blob/master/actionview/lib/action_view/helpers/tags/radio_button.rb#L20

:formタグが

このを生成する方法を

詳細はradio_buttonのコードです

def render options = @options.stringify_keys options["type"] = "radio" options["value"] = @tag_value options["checked"] = "checked" if input_checked?(object, options) add_default_name_and_id_for_value(@tag_value, options) tag("input", options) end 

タグヘルパーHTMLタグを生成し、彼のようなHTMLサフェド文字列を返す:あなたの答えのための

https://github.com/casunlight/rails/blob/master/actionview/lib/action_view/helpers/tag_helper.rb#L67

def tag(name, options = nil, open = false, escape = true) 
    "<#{name}#{tag_options(options, escape) if options}#{open ? ">" : " />"}".html_safe 
end 
+0

感謝を。初心者では、ほとんどの場合、私は '<%= f.label:attr%><%= f.radio_button:attr%>'のようにヘルパーを作成しますが、ここで 'form.label 'のようなブロックを使用しています。 }、class: 'radio-inline' do form.radio_button(:star、status)+ i18n_star(status) end'です。私はこれで混乱しています –

+0

はい、ブロックのコードをフォームのラベルメソッドに渡すことができます。メソッド定義 'def label(object_name、method、content_or_options = nil、options = nil、&block)の最後のパラメータ'&block' 'https://github.com/casunlight/rails/blob/master/actionview/lib/action_view/helpers /form_helper.rb#L750 –

+0

多くのおかげで、あなたは理解しやすくなりました。 –

関連する問題