I wanted a better way to manage common lists of simple data. More like the way enums work, but I wanted these lists managed in the database, not in the code base.
“gem ‘rails_enum_type’, git: ‘github.com/davidabenson/rails_enum_type.git’”
bundle install
rails generate rails_enum_type:install
rake db:migrate
Adds two tables to track the enum lists, type, and type_item
type_item_view joins the type and type_item tables I.E. select * from type_item_view where type = 'Color'
gem_test_dev=> select * from type;
id | name | description
—--------
————-
1 | Color |
gem_test_dev=> select * from type_item; id | type_id | name | description | sequence | sub_type —----------
——--------------
———-+———- 1 | 1 | Red | | 1.0 | 2 | 1 | Green | | 2.0 | 3 | 1 | Blue | | 3.0 |
gem_test_dev=> select * from type_item_view; type_id | type | type_item_id | type_item | description | sequence ———-------
————–-----------
————-+———-
1 | Color | 1 | Red | | 1.0 1 | Color | 2 | Green | | 2.0 1 | Color | 3 | Blue | | 3.0
class ColorType < ET::EnumType
TYPE_NAME = 'ColorType' class << self; class_attribute :type_name self.type_name = TYPE_NAME ET::EnumType.load_type_items(self.type_name, definer_method = method(:define_method), order=:sequence) end default_scope { where(type_id: ET::Type.find_by_name(self.type_name).id) }
end
house.color.id == ColorType.red.id
ColorType.all.each |color| do Rails.logger.debug("#{color.id}, #{color.name}") end
Notably the TypeItem class is gone and replaced with the database model. This allows the EnumType derived class to have associations to other model objects
This project rocks and uses MIT-LICENSE.