2

I wanna achieve the following to display in rails app:

Product instance => "product"
ProductCustomer instance => "product customer"

so I could do

<%= form_for([commentable, Comment.new]) do |f| %>
  <%= f.text_field :body, class: "form-control", id: "comment-text-area-#{commentable.id}", 
    placeholder: "Ask something about the #{commentable.class.name.split(/(?=[A-Z])/).join(' ').downcase }" %>
  ......
<% end %>

At the moment I'm using the following which works in all cases:

p = Product.new
p.class.name.split(/(?=[A-Z])/).join(' ').downcase

pc = ProductCustomer.new
pc.class.name.split(/(?=[A-Z])/).join(' ').downcase

My problem is that it seems to be too complex. I guess there should be a better way. Any ideas?

2 Answers 2

6

Use ActiveModel::Naming instead. Its a wonderful API for getting stuff like human names, route keys and I18n keys from model classes or instances.

human(options={})
Transform the model name into a more humane format, using I18n. By default, it will underscore then humanize the class name.

placeholder: "Ask something about the #{ commentable.model_name.human }"

Note that you should provide <label> elements for your inputs and not just placeholder attributes for accessibility.

Labels:

In Rails you frequently use ActionView::Helpers::FormBuilder#label:

<%= form_for([commentable, Comment.new]) do |f| %>
  <%= f.label :body %>
  <%= f.text_field :body %>
<% end %>

Which creates a label with a name attribute tied to the ID of the input. However for this to work the Rails Way you need to let the form builder set the ID of the input.

For hiding elements I usually use the Zurb Foundation .show-for-sr class which basically works like in the WAI tutorial:

.show-for-sr {
  position: absolute !important;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
}
Sign up to request clarification or add additional context in comments.

2 Comments

max, your note regarding the label is super useful. Could you tell me which approach you usually take from that list?
max, pls also see my previous comment. In the meantime I posted another question. Could you pls take a look at it? Your answers to my questions are always outstanding and easy to understand, so would be nice to see your opinion. stackoverflow.com/questions/37303420/…
2

Yes you can do this: commentable.model_name.human

In Rails calling model_name on an ActiveRecord model returns an instance of ActiveModel::Name which provides a useful api to interact with the model name.

1 Comment

I had published it a little too early, when it was an incomplete one liner. In the minute it took me to edit it, a diligent SO bee had already defrocked me :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.