Search code examples
htmlruby-on-railsrubyyamlslim

Changing text based on the final letter of user name


In my system, users will register their names. In the natural language the system is used with, names end differently depending its use, such as:

  • who: "name surname"
  • with who: "namai surnamai"

Due to this, I need to change the ending of @provider_user.name in some places; if it ends with e, replace e with ai.

My HTML slim code is:

= render partial: 'services/partials/messages/original_message', locals: { header: t('html.text.consultation_with.for_provider', name: @provider_user.name)

It takes text from a yml file and uses @provider_user.name.

Any suggestions to work this around?


Solution

  • Try this, simple single line code

    @provider_user.name.split.map {|w| (w.end_with?('e') ? (w.chomp(w[w.length - 1]) + 'ai') : w) }.join(" ")
    

    I am sure, it will convert "name surname" to "namai surnamai".

    In additional cases...

    @provider_user.name.split.map {|w| (w.end_with?('e') ? (w.chomp(w[w.length - 1]) + 'ai') : (w.end_with?('us') ? (w.chomp(w[w.length - 1]) + 'mi') : (w.end_with?('i') ? (w.chomp(w[w.length - 1]) + 'as') : w))) }.join(" ")