Skip to content

Commit

Permalink
Allow label text to be nil
Browse files Browse the repository at this point in the history
#1028 (comment)

> Actually I may have overthought this. Lucky wants to avoid bugs,
but also be practical. Sometimes nils can sneak in when you don't expect
it...but maybe label_text is not one of those places. I have a hard time
seeing a use case where someone is conditionally generating a label and
it might accidentally be nil. I think of all the apps I've ever written
I've never accidentally set label text to nil.

> So I think what I'll do is make the label text String?. So that if you
pass nil to text it will infer the label name like it does now when you
leave the arg off completely. That way we can still keep the component
flexible by allowing String? but we also keep label_for flexible. I'll
go ahead and make that change now. This also means existing apps will
still work when you upgrade and this will no longer be a breaking change
👍
  • Loading branch information
paulcsmith committed Mar 14, 2020
1 parent 521647f commit 443b17f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
10 changes: 10 additions & 0 deletions spec/lucky/label_helpers_spec.cr
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
require "../spec_helper"

include ContextHelper

class TestUser
def first_name
"My Name"
Expand Down Expand Up @@ -31,6 +33,10 @@ private class TestPage
label_for form.first_name, class: "best-label"
end

def label_with_nil_text
label_for form.first_name, text: nil
end

def label_with_custom_text
label_for form.first_name, "My Label"
end
Expand Down Expand Up @@ -61,6 +67,10 @@ describe Lucky::LabelHelpers do
<label for="user_first_name" class="best-label">First name</label>
HTML

view.label_with_nil_text.to_s.should contain <<-HTML
<label for="user_first_name">First name</label>
HTML

view.label_with_custom_text.to_s.should contain <<-HTML
<label for="user_first_name">My Label</label>
HTML
Expand Down
16 changes: 6 additions & 10 deletions src/lucky/tags/label_helpers.cr
Original file line number Diff line number Diff line change
@@ -1,15 +1,7 @@
module Lucky::LabelHelpers
def label_for(field : Avram::PermittedAttribute, **html_options)
label_for(
field,
Wordsmith::Inflector.humanize(field.name.to_s),
**html_options
)
end

def label_for(field : Avram::PermittedAttribute, text : String, **html_options)
def label_for(field : Avram::PermittedAttribute, text : String? = nil, **html_options)
label(
text,
text || guess_label_name(field),
merge_options(html_options, {"for" => input_id(field)})
)
end
Expand All @@ -28,4 +20,8 @@ module Lucky::LabelHelpers
Lucky::InputHelpers.error_message_for_unallowed_field
yield
end

private def guess_label_name(field)
Wordsmith::Inflector.humanize(field.name.to_s)
end
end

0 comments on commit 443b17f

Please sign in to comment.