This dynamic method will create a set of constants for the class/model from the table it’s associated with. The model class must have a table with two columns ( name = “constant name”, id = “constant id”).
These constants can be accessed by class methods. Ex: Role.editor() will get the instance created from the row with name of “editor”
Usage in Model class:
acts_as_constant # default constant name will be in the table's column 'name'
acts_as_constant :fooby # constant name will be in the table's column 'fooby'
Usage by client:
Role.get(2) - Get the Role instance created from row 2 in the roles table.
Role.contributer - Get the Role instance created from the row with a name of "contributer".
Implementation
Create an array class attribute named _CONSTANTS. ex: ROLE_CONSTANTS Create 2 public class methods. ex: Role.get(id) – get the Role instance in ROLE_CONSTANTS Role.CONSTANTS – get the entire ROLE_CONSTANTS array Create an instance of the class for each row in the class’s table. Role instance 1 = {“name” => “contributer”, “id” => “1” } Role instance 2 = {“name” => “editor”, “id” => “2” } Add each of these Role instances to the ROLE_CONSTANT array. The instance will be indexed in the array by the row’s id value. ROLE_CONSTANT1 = {“name” => “contributer”, “index” => “1” } ROLE_CONSTANT2 = {“name” => “editor”, “index” => “2” } Freeze each Role instance. Add 2 more public class methods. Role.contributer – returns the Role instance in ROLE_CONSTANTS1 Role.CONTRIBUTER – returns the Role instance in ROLE_CONSTANTS1 Freeze the array class attribute. ROLE_CONSTANTS