Skip to content

Commit

Permalink
Merge pull request rails#3665 from wildchild/label_i18n_3-1-stable
Browse files Browse the repository at this point in the history
Fix impractical I18n lookup in nested fields_for (3-1-stable)
  • Loading branch information
josevalim committed Nov 17, 2011
2 parents 3bcb247 + 1d8c576 commit 78f649e
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
10 changes: 9 additions & 1 deletion actionpack/lib/action_view/helpers/form_helper.rb
Expand Up @@ -983,8 +983,16 @@ def to_label_tag(text = nil, options = {}, &block)
label_tag(name_and_id["id"], options, &block)
else
content = if text.blank?
object_name.gsub!(/\[(.*)_attributes\]\[\d\]/, '.\1')
method_and_value = tag_value.present? ? "#{method_name}.#{tag_value}" : method_name
I18n.t("helpers.label.#{object_name}.#{method_and_value}", :default => "").presence

if object.respond_to?(:to_model)
key = object.class.model_name.i18n_key
i18n_default = ["#{key}.#{method_and_value}".to_sym, ""]
end

i18n_default ||= ""
I18n.t("#{object_name}.#{method_and_value}", :default => i18n_default, :scope => "helpers.label").presence
else
text.to_s
end
Expand Down
46 changes: 46 additions & 0 deletions actionpack/test/template/form_helper_test.rb
Expand Up @@ -27,7 +27,13 @@ def setup
:body => "Write entire text here",
:color => {
:red => "Rojo"
},
:comments => {
:body => "Write body here"
}
},
:tag => {
:value => "Tag"
}
}
}
Expand Down Expand Up @@ -68,6 +74,12 @@ def @post.to_param; '123'; end
@post.secret = 1
@post.written_on = Date.new(2004, 6, 15)

@post.comments = []
@post.comments << @comment

@post.tags = []
@post.tags << Tag.new

@blog_post = Blog::Post.new("And his name will be forty and four.", 44)
end

Expand Down Expand Up @@ -151,6 +163,40 @@ def test_label_with_locales_and_value
I18n.locale = old_locale
end

def test_label_with_locales_and_nested_attributes
old_locale, I18n.locale = I18n.locale, :label
form_for(@post, :html => { :id => 'create-post' }) do |f|
f.fields_for(:comments) do |cf|
concat cf.label(:body)
end
end

expected = whole_form("/posts/123", "create-post" , "edit_post", :method => "put") do
"<label for=\"post_comments_attributes_0_body\">Write body here</label>"
end

assert_dom_equal expected, output_buffer
ensure
I18n.locale = old_locale
end

def test_label_with_locales_fallback_and_nested_attributes
old_locale, I18n.locale = I18n.locale, :label
form_for(@post, :html => { :id => 'create-post' }) do |f|
f.fields_for(:tags) do |cf|
concat cf.label(:value)
end
end

expected = whole_form("/posts/123", "create-post" , "edit_post", :method => "put") do
"<label for=\"post_tags_attributes_0_value\">Tag</label>"
end

assert_dom_equal expected, output_buffer
ensure
I18n.locale = old_locale
end

def test_label_with_for_attribute_as_symbol
assert_dom_equal('<label for="my_for">Title</label>', label(:post, :title, nil, :for => "my_for"))
end
Expand Down

0 comments on commit 78f649e

Please sign in to comment.