Rails usually uses strings (for notifications and error messages, etc.)

About a year ago, I decided to make sure that every flash notification that had unique text will receive text from a method in the module. My original reason for this was not to print the same line again and again. If I wanted to change the wording, I could do it easily in one place, and the chance of typos repeating the same thing over and over will be reduced.

What I ended up with:

module Messages
    def format_error_messages(errors)
        errors.map {|attribute, message| "Error: #{attribute.to_s.titleize} #{message}.<br />"}
    end

    def error_message_could_not_find(object_name)
        "Error: Unable to find the specified " + object_name + "!"
    end

    def error_message_could_not_create(object_name)
        "Error: Unable to create the " + object_name + "!"
    end

    def error_message_could_not_save(object_name)
        "Error: Unable to save " + object_name + " to database!"
    end

    def error_message_could_not_update(object_name)
        "Error: Unable to update " + object_name + "!"
    end

    def error_message_could_not_destory(object_name)
        "Error: Unable to destroy " + object_name + "!"
    end

    def notice_message_created(object_name)
        object_name.capitalize + " has been created!"
    end

    def notice_message_updated(object_name)
        object_name.capitalize + " has been updated!"
    end

    def notice_message_destroyed(object_name)
        object_name.capitalize + " has been deleted!"
    end
end

In my controllers, when I configure flash, I can do something like:

flash[:notice] = notice_message_created("post")

Thus, all successfully created objects generate similar messages.

, , , . , , , , - , , . , , . (, , )?

Rails, ? , , ?

Rails, , , YAML, . , , , ( , , ).

, .

+5
2

Rails API . , . , , , , 4.2 .

I18n.backend.store_translations :en, :thanks => 'Thanks %{name}!'
I18n.translate :thanks, :name => 'Jeremy'
# => 'Thanks Jeremy!'

:

  • config/locales/en.yml

  • :

    : created: "# {name} !"

  • notice_message_created(object_name) : t(:created, object_name.capitalize)

-, , , config/locales.

+5

I18N. , , , , , .

Rails I18N interpolation, , , ,

, " "?

+3

All Articles