0.0
No commit activity in last 3 years
No release in over 3 years
Easily create localization-friendly constant lists
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Runtime

 Project Readme

ListsConstant

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.

Installation

Add this line to your application's Gemfile:

gem 'lists_constant'

And then execute:

$ bundle

Or install it yourself as:

$ gem install lists_constant

Usage

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'

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request