Bye
Bye

Reputation: 768

Rails: understanding custom form helper

new.html.erb

<%= 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

I saw a piece of code like above.
I am not familiar with custom form helper.
Could you let me know why we can use form.radio_button(:star, status) + i18n_star(status) inside a block and why we can use '+' to add text on radio buttons.
I will be appreciated if you could tell me where I can go to learn this.

Upvotes: 1

Views: 182

Answers (1)

Alex Kojin
Alex Kojin

Reputation: 5204

form.radio_button helper returns a string and I18n.t too returns a string. So, you can concatenate them.

More details how form tag is generated

This is a code of radio_button:

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

Look at implementation of render method

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

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

Tag helper generate html tag and return his as html safed string:

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

Upvotes: 1

Related Questions