Helper methods to display translated values of object attributes.
Add this line to your application's Gemfile:
gem 'translateable_attributes'And then execute:
$ bundle
Or install it yourself as:
$ gem install translateable_attributes
Setup your translations:
en:
states:
new: 'Initiated'
completed: 'Done'Extend a class with TranslateableAttributes::Methods and call translate_attributes method on it:
class TranslatedClass
extend TranslateableAttributes::Methods
translate_attributes state: 'states'
endUse translated_attribute class and instance methods to display translated values:
TranslatedClass.translated_state('new') #=> 'Initiated'
translated_instance = TranslatedClass.new
translated_instance.state = 'new'
translated_instance.translated_state #=> 'Initiated'In addition, attributes_for_select class method is defined that returns all available [translation, value] pairs - useful for select inputs in Rails form builders.
TranslatedClass.states_for_select #=> [['Initiated', 'new'], ['Done', 'completed']]translate_attributes class method accepts a hash of attribute_name: 'translation.namespace'. Translations are looked up by appending attribute value to provided namespace and passing that to I18n.t method.
For example, given Klass.translate_attributes state: 'some.nested.translation.namespace', calling Klass.translated_state 'new' equals to I18n.t 'some.nested.translation.namespace.new'.
After checking out the repo, run bin/setup to install dependencies. Then, run bin/console for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release to create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.
- Fork it ( https://github.com/tmikoss/translateable_attributes/fork )
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create a new Pull Request