Noob: HOWTO Externalize Strings?


#1

Hi all,

I’m totally new to Rails and was wondering how to externalize message
strings in a file so I can use them throughout my application. Is
there something already provided with Rails ?

Thanks

Thogra


#2

Thogra

I’m totally new to Rails and was wondering how to externalize
message
strings in a file

In environment.rb:

load the strings file :

APP_TEXT = YAML::load(File.open("#{RAILS_ROOT}/config/messages.yml"))
rescue {}

In config/message.yml:
db_save:
success: Success
failure: Failure

In views/controller: example:

flash[:notice] = tx_(‘db_save/success’)

In application.rb

def dev?
@is_dev||=(ENV[‘RAILS_ENV’]==‘development’)
end
def tx_(key)
a,b = key.split(’/’)
APP_TEXT[a][b]+(dev? ? ‘°’ : ‘’)
end
helper_method :tx_, :dev?

Note: this version adds a little ° after externalized string when in
dev mode => you can see what’s hardcoded, and what’s externalized.

Alain


#3

Thanks Alain, this helped me a lot !!


#4

I was excpecting the ‘tx_(key)’ method to be available in functional
test as well if defined in application.rb. But it isn’t.

Do I have to duplicate the method(s) ? If, what would be the right
place for it ? test_helper.rb ?