ListsConstant is a module which allows you to easily define lists of constant values. I18n is used to translate the listed constants into readable values.
This library is intended to make it simple to keep view-specific information (like the text representations of your listed values) out of your model classes.
Add this line to your application's Gemfile:
gem 'lists_constant'
And then execute:
$ bundle
Or install it yourself as:
$ gem install lists_constant
Example:
In my_state_machine.rb
:
class MyStateMachine
include ListsConstant
lists_constant :first, :second, :third, as: :steps
attr_accessor :step
def initialize(step)
@step = step
end
end
In locales/en.yml
:
en:
my_state_machine:
steps:
first: Initialize
second: Validate
third: Save
In locales/es.yml
:
es:
my_state_machine:
steps:
first: Inicie
second: Valide
third: Guarde
Using the generated constant:
MyStateMachine::STEPS
# => [:first, :second, :third]
Class-level localization:
I18n.locale = :en
MyStateMachine.steps[:first]
# => 'Initialize'
MyStateMachine.localized_step('second')
# => 'Validate'
MyStateMachine.step_options
# => {
# 'Initialize' => :first,
# 'Validate' => :second,
# 'Save' => :third
# }
I18n.locale = :es
MyStateMachine.steps[:first]
# => 'Inicie'
Class query method:
MyStateMachine.includes_step? :first
# => true
MyStateMachine.includes_step? 'second'
# => true
MyStateMachine.includes_step? 'profit!'
# => false
Instance-level localization:
I18n.locale = :en
msm.localized_step
# => 'Validate'
I18n.locale = :es
msm.localized_step
# => 'Valide'
Instance query methods:
msm = MyStateMachine.new(:second)
msm.step_second?
# => true
msm.step_third?
# => false
Localization lookups may be scoped by assigning a namespace to
the ListsConstant
module:
en:
activerecord:
attributes:
my_state_machine:
steps:
...
ListsConstant.namespace = 'activerecord.attributes'
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Added some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request