active_finite¶ ↑
Compatibility notes¶ ↑
This gem does not work with newer versions of ruby, or of rails. It currently works with versions of ruby before 1.9.3, and with with other versions specified in the Gemfile. To run tests, use:
rbenv exec bundle _1.0.22_ exec rake gemspec
There are no plans on porting this to new versions unless there is interest. You can ask for porting by adding an issue to active_finite’s github page.
What is active_finite?¶ ↑
The goal of active_finite is to provide a simple way to define database enumerations with ActiveRecord. There are many existing projects that bring some enum support to ActiveRecord. However, these projects tend to define the enums in code, instead of in the migration itself.
Hello, active_finite!¶ ↑
Let’s start by defining a simple migration:
require 'active_finite' require 'active_record' require 'active_support/core_ext' class Hellos < ActiveRecord::Migration self.up add_finites in_table: :hellos, values: ['oy', 'que tal', 'hi'] end self.down delete_finites in_table: :hellos, values: ['oy', 'que tal', 'hi'] end end
Now that we some hellos in our Hello model, we can access them using:
hellos = get_table :hellos
The variable hellos now holds a class derived from ActiveRecord named Hello, so all of the normal ActiveRecord methods can be used.
We can also a collection of all of the active record classes defined by active_finite by using:
all_finite_tables
Using get_table and all_finite_tables implicitly bring the associated classes into scope, so a single call to all_finite_tables is sufficent to define all of the models.
Other options¶ ↑
If the column name must be different than the default, the column_name option can be used. Also, a json file can be used instead of explicitly listing the possible values in the migration. For example:
require 'active_finite' require 'active_record' require 'active_support/core_ext' class HellosWithCustomColumn < ActiveRecord::Migration self.up add_finites in_table: :hellos, values: ['oy', 'que tal', 'hi'] column_name: :custom from_file: 'hellos.json' end self.down delete_finites in_table: :hellos, values: all end end
If both values and from_file are defined, active_finite will pull entries from both. Another option to be aware of is that values do not have to be explicitly listed upon deletion, using the all option is sufficent.