Tuesday, June 2, 2009

Messages in Ruby/JRuby using Constants in a Module

If you want to share messages between Ruby/JRuby classes but don't want to use i18n/l10n because it is unnecessary, then a good way to do it is via defining constants in a module. (In Java, this would be analogous to defining constants in an interface.)

Let's assume this goes into the file lib/somesubpart/mymessages.rb:

module SomeProjectName
  module SomeSubpartOfProject 
    PLEASE_CONTACT_SUPPORT_IF_NEED_HELP = "Please contact the office at 123-4567 if you need assistance."
    SOMETHING_ELSE = "This is really something else!"
  end
end

To use those in a ruby class (assuming you put those into lib/somesubpart/mymessages.rb), you could print those two messages like this:

require 'lib/somesubpart/mymessages'
...
p SomeProjectName::SomeSubpartOfProject::PLEASE_CONTACT_SUPPORT_IF_NEED_HELP
p SomeProjectName::SomeSubpartOfProject::SOMETHING_ELSE

No comments: