Skip to content

davidabenson/rails_enum_type

Repository files navigation

Rails Enum Type

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.

Install

“gem ‘rails_enum_type’, git: ‘github.com/davidabenson/rails_enum_type.git’”

bundle install

rails generate rails_enum_type:install

rake db:migrate

Added Tables

Adds two tables to track the enum lists, type, and type_item

Added View

type_item_view joins the type and type_item tables
I.E.  select * from type_item_view where type = 'Color'

Example Color = [Red,Green,Blue] is preloaded as an example

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

app/model/color_type.rb

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

Comparison Example

house.color.id == ColorType.red.id

Looping example

ColorType.all.each |color| do
    Rails.logger.debug("#{color.id}, #{color.name}")
end

Note: Version 1, had some pretty big changes over version 0.0.1.

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.

About

Database table backed enum lists

Resources

License

Stars

Watchers

Forks

Packages

No packages published