Szilard Magyar Szilard Magyar - 1 year ago 30
Ruby Question

Add the name of a model to a string in Rails

I wanna achieve the following to display in rails app:

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

so I could do

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

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

p =[A-Z])/).join(' ').downcase

pc =[A-Z])/).join(' ').downcase

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

max max

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

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.


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

<%= form_for([commentable,]) 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);