Forum: Ruby on Rails Where to put localization strings

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Hans-eric G. (Guest)
on 2006-04-28 13:22
Hello!

I have a model that validates presence of the attribute title

class Entry < ActiveRecord::Base
  validates_presence_of :title
    :message => 'empty title is a no no'
end

I also have a test of this valitation.

class EntryTest < Test::Unit::TestCase
  fixtures :entries

  def test_validate_title
    first = entries(1)
    first.title = ''
    assert !first.save
    assert_equal 1, first.errors.count
    assert_equal 'empty title is a no no', first.errors.on(:title)
  end
end

The thing is I want to replace the hard coded message strings with a
constant. Where should I put this constant according to best practice?
I'm thinking of creating a new module for this, but maybe there's a
better way?

Best regards

Hans-Eric Grönlund - a newly hatched rails enthusiast
Ilan B. (Guest)
on 2006-04-28 21:32
I would suggest installing the localization generator.. I forget the
exact name but in can easily be found by 'gem search localization -r'

or by following this link http://rubyforge.org/projects/localization

From this amazing generator, you simply create one yaml file for each
external language you want to support.

in your specific example, you could do something like:
class Entry < ActiveRecord::Base
  validates_presence_of :title
    :message => l(empty_string_message)

where l() is a helper method in the localization gem that automatically
converts to the language specified in your environment

Then your test case would be something like like:

assert_equal l(empty_string_message), first.errors.on(:title)

I hope this helps and I am pretty new to rails myself but this gem is a
beauty and it couldn't be simpler to work with!

ilan


Hans-Eric Grönlund wrote:
> Hello!
>
> I have a model that validates presence of the attribute title
>
> class Entry < ActiveRecord::Base
>   validates_presence_of :title
>     :message => 'empty title is a no no'
> end
>
> I also have a test of this valitation.
>
> class EntryTest < Test::Unit::TestCase
>   fixtures :entries
>
>   def test_validate_title
>     first = entries(1)
>     first.title = ''
>     assert !first.save
>     assert_equal 1, first.errors.count
>     assert_equal 'empty title is a no no', first.errors.on(:title)
>   end
> end
>
> The thing is I want to replace the hard coded message strings with a
> constant. Where should I put this constant according to best practice?
> I'm thinking of creating a new module for this, but maybe there's a
> better way?
>
> Best regards
>
> Hans-Eric Grönlund - a newly hatched rails enthusiast
This topic is locked and can not be replied to.