### Install EnumerateIt Gem Source: https://github.com/lucascaton/enumerate_it/blob/main/README.md Install the EnumerateIt gem using the RubyGems package manager. ```bash gem install enumerate_it ``` -------------------------------- ### Example Type Specification Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/MANIFEST.md Shows a comprehensive example of how to specify types within the EnumerateIt system. This is useful for understanding the flexibility and depth of type definitions. ```ruby # Example type specification class StatusEnum < EnumerateIt::Base ... # type definitions and option combinations end ``` -------------------------------- ### Basic Enumeration Usage Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md Demonstrates basic usage of EnumerateIt for getting values and keys from an enumeration. ```ruby value = OrderStatus.value_for('PENDING') key = OrderStatus.key_for(value) # Optimization: Cache if called frequently @pending_value ||= OrderStatus::PENDING ``` -------------------------------- ### Basic Enumeration Example: UserRole Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/rails-generator.md Generates an enumeration class and locale file for user roles with basic values. ```bash rails generate enumerate_it:enum UserRole admin user guest ``` ```ruby class UserRole < EnumerateIt::Base associate_values( :admin, :user, :guest ) end ``` ```yaml en: enumerations: user_role: admin: Admin user: User guest: Guest ``` -------------------------------- ### Error Handling Example Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/MANIFEST.md Provides a real code example for handling specific error conditions, such as ArgumentError, validation errors, or NameError, within the EnumerateIt framework. Demonstrates recovery and prevention strategies. ```ruby # Example for handling validation errors begin invalid_enum = MyEnum.new(:invalid_value) rescue EnumerateIt::ValidationError => e puts "Validation Error: #{e.message}" end ``` -------------------------------- ### Import and Setup in Rails and Non-Rails Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/quick-reference.md Shows how to make enumerations available in Rails models automatically or manually extend them in non-Rails applications. ```ruby class User < ApplicationRecord has_enumeration_for :role end ``` ```ruby class Person extend EnumerateIt has_enumeration_for :status end ``` -------------------------------- ### Multi-language Enumeration Example: RelationshipStatus Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/rails-generator.md Generates an enumeration class and a Brazilian Portuguese locale file for relationship statuses. ```bash rails generate enumerate_it:enum RelationshipStatus single married divorced --lang pt-BR ``` ```ruby class RelationshipStatus < EnumerateIt::Base associate_values( :single, :married, :divorced ) end ``` ```yaml pt-BR: enumerations: relationship_status: single: Single married: Married divorced: Divorced ``` -------------------------------- ### Rails Generator Example Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/MANIFEST.md Demonstrates the usage of the Rails generator command to create an enumeration. Includes parameters and options for customization. ```bash rails generate enumerate_it:enum NAME --attributes=ATTRIBUTES --lang=LANG --singular ``` -------------------------------- ### Basic Enumeration Setup and Usage Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/00-START-HERE.md Demonstrates how to define a basic enumeration using EnumerateIt::Base, integrate it with a Rails model using has_enumeration_for, and utilize the generated helper methods for checking states, humanizing values, and creating scopes. ```ruby class Status < EnumerateIt::Base associate_values :active, :inactive, :pending end class Task < ApplicationRecord has_enumeration_for :status, create_helpers: true end task = Task.new(status: Status::ACTIVE) task.active? #=> true task.status_humanize #=> 'Active' Task.active.count #=> 42 ``` -------------------------------- ### Generated Locale File (English) Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/rails-generator.md Example of a generated locale file in English with default humanized translations. ```yaml en: enumerations: status: active: Active inactive: Inactive ``` -------------------------------- ### Authorization Integration for Status Transitions Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md Provides an example of integrating enumeration values into an authorization layer to control status transitions. ```ruby class Order < ApplicationRecord has_enumeration_for :status # Add authorization layer def allowed_status_transitions case status when OrderStatus::PENDING [OrderStatus::PROCESSING, OrderStatus::CANCELLED] when OrderStatus::PROCESSING [OrderStatus::SHIPPED, OrderStatus::PENDING] else [] end end def transition_to(new_status) raise "Not allowed" unless allowed_status_transitions.include?(new_status) update(status: new_status) end end ``` -------------------------------- ### EnumerateIt Module Usage Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/MANIFEST.md Illustrates how to use the EnumerateIt module, covering both Rails and non-Rails usage patterns. This example is relevant for understanding core module integration. ```ruby require 'enumerate_it' class MyEnum < EnumerateIt::Base ... # enum definitions end # Rails usage class MyModel < ActiveRecord::Base has_enumeration :my_enum, with: MyEnum end # Non-Rails usage my_instance = MyEnum.new(:value1) puts my_instance.key ``` -------------------------------- ### Authorization Integration with Pundit Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md Example of integrating EnumerateIt values with the Pundit gem for authorization checks. ```ruby class OrderPolicy def update? user.admin? || (user.id == record.user_id && record.pending?) end def transition_to_shipped? user.admin? && record.processing? end end ``` -------------------------------- ### Generated Enumeration Class with Basic Values Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/rails-generator.md Example of an enumeration class generated with basic, non-custom values. ```ruby class Status < EnumerateIt::Base associate_values( :active, :inactive ) end ``` -------------------------------- ### Get All Enumeration Keys Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/base.md Returns an array containing all defined enumeration key symbols. Useful for getting a list of all possible states. ```ruby class Status < EnumerateIt::Base associate_values :active, :inactive end Status.keys ``` -------------------------------- ### JSON API Response Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/quick-reference.md Render enumeration values as JSON for API responses. The example shows the expected output format for a GET request. ```ruby class UsersController < ApplicationController def roles render json: UserRole.to_json end end # GET /users/roles # [{"value":"admin","label":"Admin"},{"value":"user","label":"User"}] ``` -------------------------------- ### Configure Enumeration with All Options Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/configuration.md Demonstrates a comprehensive configuration for an enumeration, including custom values, helper methods, scopes, and presence validation with a custom message. This setup generates various query and mutation methods, polymorphic accessors, scopes, and enforces validation rules. ```ruby class User < ApplicationRecord has_enumeration_for :role, with: UserRole, create_helpers: { prefix: true, polymorphic: { suffix: '_handler' } }, create_scopes: { prefix: true }, required: { message: 'must be assigned' } end # Creates: # - role_admin?, role_user?, role_guest? query methods # - role_admin!, role_user!, role_guest! mutator methods # - role_handler polymorphic accessor # - role_admin, role_user, role_guest scopes # - Presence validation with custom message # - Inclusion validation user = User.new(role: UserRole::ADMIN) user.role_admin? #=> true user.role_handler #=> # User.role_admin #=> ActiveRecord::Relation ``` -------------------------------- ### Internationalization (I18n) Configuration Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/quick-reference.md Shows how to configure translations for enumerations in YAML files for different locales. Includes examples for simple and namespaced enumerations. ```yaml # config/locales/en.yml en: enumerations: status: active: Currently Active inactive: Not Active # For namespaced enums (Design::Color) en: enumerations: "design/color": blue: Ocean Blue red: Cherry Red ``` -------------------------------- ### Generated Locale File (Brazilian Portuguese) Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/rails-generator.md Example of a generated locale file for Brazilian Portuguese, demonstrating multi-language support. ```yaml pt-BR: enumerations: status: active: Ativo inactive: Inativo ``` -------------------------------- ### Method Naming Conventions (Default) Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/quick-reference.md When `create_helpers` is enabled, EnumerateIt generates query and mutator methods for each enumeration value. This example shows the default naming convention. ```ruby has_enumeration_for :role, create_helpers: true # Query methods: {attribute}_{value}? user.admin? # Mutator methods: {attribute}_{value}! user.admin! ``` -------------------------------- ### Iterating Through Enumerations Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/quick-reference.md Demonstrates how to iterate over enumeration values, keys, and translations using `each_value`, `each_key`, and `each_translation` blocks. Also shows how to get an array of translations. ```ruby Status.each_value { |val| puts val } # Yields: 'active', 'inactive' Status.each_key { |key| puts key } # Yields: :active, :inactive Status.each_translation { |label| puts label } # Yields: 'Active', 'Inactive' Status.translations #=> ['Active', 'Inactive'] ``` -------------------------------- ### Generated Enumeration Class with Custom Values Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/rails-generator.md Example of an enumeration class generated with custom key:value pairs. ```ruby class Status < EnumerateIt::Base associate_values( active: 1, inactive: 2 ) end ``` -------------------------------- ### keys Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/base.md Returns an array of all enumeration key symbols. This provides a direct way to get all defined keys for an enumeration. ```APIDOC ## keys ### Description Returns an array of all enumeration key symbols. ### Method `self.keys` ### Parameters None ### Request Example ```ruby class Status < EnumerateIt::Base associate_values :active, :inactive end Status.keys ``` ### Response #### Success Response `Array` — All enumeration keys. #### Response Example ```ruby [:active, :inactive] ``` ``` -------------------------------- ### ActiveRecord Model with Custom Enumeration Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/core_module.md An example of an ActiveRecord model using `has_enumeration_for` with a custom enumeration class and enabling helper methods. ```ruby # app/enumerations/user_role.rb class UserRole < EnumerateIt::Base associate_values :admin, :user, :guest end # app/models/user.rb class User < ApplicationRecord has_enumeration_for :role, with: UserRole, create_helpers: true end # Usage user = User.new(role: UserRole::ADMIN) user.admin? #=> true ``` -------------------------------- ### JSONAPI Integration Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md Example of integrating enumerate_it with JSONAPI::Serializer to define custom attributes based on enum values. ```ruby class OrderSerializer include JSONAPI::Serializer attribute :status attribute :status_label do |order| order.status_humanize end end ``` -------------------------------- ### Custom Values Enumeration Example: OrderStatus Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/rails-generator.md Generates an enumeration class and locale file for order statuses using custom numeric values. ```bash rails generate enumerate_it:enum OrderStatus pending:1 shipped:2 delivered:3 cancelled:4 ``` ```ruby class OrderStatus < EnumerateIt::Base associate_values( pending: 1, shipped: 2, delivered: 3, cancelled: 4 ) end ``` ```yaml en: enumerations: order_status: pending: Pending shipped: Shipped delivered: Delivered cancelled: Cancelled ``` -------------------------------- ### Using Translations for Enumeration Values Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/configuration.md Demonstrates how to retrieve individual translations for enumeration values using the `.t` method and how to get all translations or iterate through them. ```ruby # Get single translation Status.t('active') #=> 'Active' (from I18n or default) # Get all translations Status.translations #=> ['Active', 'Inactive', 'Pending'] # Iterate translations Status.each_translation { |label| puts label } ``` -------------------------------- ### Define Enumeration Values Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/base.md Use `associate_values` to define the keys and their corresponding values for an enumeration. This example shows simple key-value associations. ```ruby class Status < EnumerateIt::Base associate_values :active, :inactive end Status.value_from_key(:active) #=> 'active' Status.value_from_key(nil) #=> nil ``` -------------------------------- ### Get Array of Options for Rails Helpers Source: https://github.com/lucascaton/enumerate_it/blob/main/README.md The `to_a` method provides an array suitable for use with Rails form helpers like `select` and `select_tag`. ```ruby RelationshipStatus.to_a #=> [['Divorced', 'divorced'], ['Married', 'married'], ['Single', 'single']] ``` -------------------------------- ### Composite Enumerations for Complex State Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md Combine multiple enumerations for complex state management. This example shows a `WorkOrder` with `status` and `priority` enumerations. ```ruby class WorkOrder < ApplicationRecord has_enumeration_for :status, create_helpers: true has_enumeration_for :priority, create_helpers: true scope :high_priority_pending, -> { where(status: OrderStatus::PENDING, priority: Priority::HIGH) } def urgent? pending? && priority == Priority::HIGH end end order = WorkOrder.find(1) order.urgent? #=> true ``` -------------------------------- ### Apply Prefix Option to Custom Instance Helpers Source: https://github.com/lucascaton/enumerate_it/blob/main/README.md Demonstrates how the `prefix` option, when used with `create_helpers`, also applies to custom helper methods. ```ruby class Person < ApplicationRecord has_enumeration_for :relationship_status, with: RelationshipStatus, create_helpers: { prefix: true } end person = Person.new(relationship_status: RelationshipStatus::DIVORCED) person.relationship_status_ever_married? #=> true ``` -------------------------------- ### Get Range of Enumeration Values Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/base.md Use `to_range` to get a `Range` object representing the minimum to maximum values of a numeric enumeration. This is useful for numeric enumerations. ```ruby class Priority < EnumerateIt::Base associate_values low: 1, medium: 2, high: 3 end Priority.to_range #=> 1..3 ``` -------------------------------- ### Create Helpers with All Options Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/types.md Combine `prefix` and `polymorphic` options to generate both prefixed query methods and a polymorphic object accessor with a custom suffix. ```ruby has_enumeration_for :status, create_helpers: { prefix: true, polymorphic: { suffix: '_mode' } } ``` -------------------------------- ### Get All Enumeration Translations Source: https://github.com/lucascaton/enumerate_it/blob/main/README.md The `translations` method returns all the translations associated with the enumeration. ```ruby RelationshipStatus.translations ``` -------------------------------- ### View Generator Help Information Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/rails-generator.md Run this command to display the available options and usage instructions for the `enumerate_it:enum` generator. ```bash rails generate enumerate_it:enum --help ``` -------------------------------- ### Humanize Enumeration Value Source: https://github.com/lucascaton/enumerate_it/blob/main/README.md Illustrates how to get a human-readable string for an enumeration value. This method is automatically generated. ```ruby p = Person.new p.relationship_status = RelationshipStatus::DIVORCED p.relationship_status_humanize #=> 'Divorced' ``` -------------------------------- ### Get Number of Enumeration Values Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/base.md The `length` method returns the total count of defined enumeration values. ```ruby class Status < EnumerateIt::Base associate_values :active, :inactive end Status.length #=> 2 ``` -------------------------------- ### Get Enumeration with I18n Translations Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/base.md When I18n is configured, `to_a` will use translated labels for enumeration values. ```ruby # config/locales/en.yml # enumerations: # status: # active: Currently Active # inactive: Not Active # Status.to_a #=> [['Currently Active', 'active'], ['Not Active', 'inactive']] ``` -------------------------------- ### Create Helpers with Prefixed Methods Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/types.md Use `create_helpers: { prefix: true }` to generate prefixed query methods such as `status_active?`. ```ruby has_enumeration_for :status, create_helpers: { prefix: true } ``` -------------------------------- ### Get List of Enumeration Codes Source: https://github.com/lucascaton/enumerate_it/blob/main/README.md The `list` method returns an array of all defined enumeration codes in the order they were associated. ```ruby RelationshipStatus.list #=> ['divorced', 'married', 'single'] ``` -------------------------------- ### Pagination with Kaminari/Will_Paginate Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md Shows how to use EnumerateIt scopes with pagination gems like Kaminari or Will_Paginate. ```ruby Order.shipped.page(1) Order.pending.per(10).page(2) ``` -------------------------------- ### t Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/base.md Translates a specific enumeration value to its human-readable label. Use this to get the display name for a given enumeration value. ```APIDOC ## t ### Description Translates a specific enumeration value to its human-readable label. ### Method `self.t(value)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **value** (String, Integer) - Required - The enumeration value to translate ### Request Example ```ruby class Status < EnumerateIt::Base associate_values :active, :inactive end Status.t('active') ``` ### Response #### Success Response `String` — Translated label or the value itself if not found. #### Response Example ```ruby 'Active' ``` ``` -------------------------------- ### Enumeration Validation Options Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md Illustrates different ways to set up enumeration validation, including skipping validation for performance. ```ruby # Validates against enumeration.list # Efficient for small enumerations has_enumeration_for :status # Very fast - No validation has_enumeration_for :status, skip_validation: true ``` -------------------------------- ### Minimal Configuration for Enumeration Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/configuration.md Sets up a basic enumeration for the `:role` attribute, inferring the class name and adding inclusion validation. ```ruby class User < ApplicationRecord has_enumeration_for :role end ``` -------------------------------- ### Get Enumeration as Hash Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/base.md The `to_h` method returns a hash mapping enumeration symbol keys to their associated values. ```ruby class Priority < EnumerateIt::Base associate_values high: 1, low: 2 end Priority.to_h #=> { high: 1, low: 2 } ``` -------------------------------- ### Use Enumerations in Application Logic Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md Demonstrates how to create, query, and update model instances using the integrated enumeration. Includes usage of generated helper methods, scopes, and custom helpers. ```ruby # Create order order = Order.create(status: OrderStatus::PENDING) # Query using helpers order.pending? #=> true order.status_humanize #=> 'Pending' # Use scopes Order.pending.count #=> 42 Order.shipped.or(Order.delivered) # Check custom helper OrderStatus.completed?(order.status) #=> false # Update status order.delivered! order.status_humanize #=> 'Delivered' order.delivered? #=> true ``` -------------------------------- ### Get EnumerateIt Gem Version Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/exported-symbols.md Access the current version of the EnumerateIt gem using the EnumerateIt::VERSION constant. ```ruby EnumerateIt::VERSION #=> "4.2.0" Gem.loaded_specs['enumerate_it'].version # Alternative ``` -------------------------------- ### Require EnumerateIt Gem Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/exported-symbols.md Demonstrates how to require the main EnumerateIt gem, making all its core components available. ```ruby # Everything from main gem require 'enumerate_it' ``` -------------------------------- ### Dynamic Enumeration Building (Not Recommended) Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md Dynamically building enumerations from data sources like the database is possible but generally not recommended as it can defeat the purpose of using enumerations for defined states. ```ruby # Only for complex requirements; typically avoid class DynamicStatus < EnumerateIt::Base Config.statuses.each do |status| # Don't do this in practice - defeats purpose of enumerations end end ``` -------------------------------- ### Get Value for a Specific Enumeration Constant Source: https://github.com/lucascaton/enumerate_it/blob/main/README.md The `value_for` method returns the string value associated with a given enumeration constant. ```ruby RelationshipStatus.value_for('MARRIED') #=> 'married' ``` -------------------------------- ### Get All Translated Labels Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/base.md Returns an array of all translated labels for enumeration values. Useful for displaying a list of human-readable states. ```ruby class Status < EnumerateIt::Base associate_values :active, :inactive end Status.translations ``` -------------------------------- ### Handling N+1 Issues with Custom Helpers Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md Demonstrates how to avoid N+1 query problems when using custom enumeration helper methods in loops. ```ruby # Watch out - N+1 if checking custom helpers in loop orders.each { |o| puts o.status_humanize } # Better - Batch load orders.load.each { |o| puts o.status_humanize } ``` -------------------------------- ### Access EnumerateIt Version Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/exported-symbols.md Illustrates how to access the version constant of the EnumerateIt gem. ```ruby # Version EnumerateIt::VERSION ``` -------------------------------- ### Access Custom Instance Helper Methods with create_helpers Source: https://github.com/lucascaton/enumerate_it/blob/main/README.md Shows how custom helper methods defined in the enumeration class become instance methods on the model when `create_helpers: true` is used. ```ruby class Person < ApplicationRecord has_enumeration_for :relationship_status, with: RelationshipStatus, create_helpers: true end person = Person.new(relationship_status: RelationshipStatus::DIVORCED) person.ever_married? #=> true ``` -------------------------------- ### Create Helpers with Boolean Option Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/types.md Set `create_helpers` to true to generate basic query methods like `active?`. ```ruby has_enumeration_for :status, create_helpers: true ``` -------------------------------- ### Get Values for Specific Enumeration Constants Source: https://github.com/lucascaton/enumerate_it/blob/main/README.md Use `values_for` to retrieve a list of values corresponding to a given group of enumeration constants. ```ruby RelationshipStatus.values_for %w(MARRIED SINGLE) #=> ['married', 'single'] ``` -------------------------------- ### Defining Immutable Enumerations Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md Illustrates the correct way to define enumerations at load time to ensure immutability. ```ruby # Good - Define at load time class Status < EnumerateIt::Base associate_values :active, :inactive end # Avoid - Dynamic at runtime class Status < EnumerateIt::Base if ENV['ADVANCED_MODE'] associate_values :active, :inactive, :suspended else associate_values :active, :inactive end end ``` -------------------------------- ### Get Enumeration as JSON Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/base.md The `to_json` method returns a JSON string representing the enumeration as an array of objects, each with `value` and `label` keys. ```ruby class Status < EnumerateIt::Base associate_values :active, :inactive end Status.to_json #=> "[{"value":"active","label":"Active"},{"value":"inactive","label":"Inactive"}]" ``` -------------------------------- ### Manual Class Extension with EnumerateIt Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/core_module.md Demonstrates how to manually extend a class with EnumerateIt and define an enumeration for an attribute. This is useful when not using ActiveRecord. ```ruby class Person extend EnumerateIt attr_accessor :status has_enumeration_for :status end person = Person.new person.status = 'active' ``` -------------------------------- ### Get List of Enumeration Values Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/base.md The `list` method returns an array of all enumeration values, sorted according to the configured `sort_by` mode. ```ruby class Status < EnumerateIt::Base associate_values :active, :inactive end Status.list #=> ['active', 'inactive'] ``` -------------------------------- ### Define Enumeration Values and Custom Helpers Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md Define enumeration values, manage translations, and provide custom helper methods for specific enumeration states. This is the first step in setting up an enumeration. ```ruby class OrderStatus < EnumerateIt::Base associate_values :pending, :processing, :shipped, :delivered, :cancelled sort_by :translation custom_helpers do def completed?(value) [DELIVERED].include?(value) end def is_final?(value) [DELIVERED, CANCELLED].include?(value) end end end ``` -------------------------------- ### Polymorphic Enumeration Objects Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md Demonstrates how to use `create_helpers: { polymorphic: true }` to associate polymorphic objects with enumeration values. This allows each enumeration state to have its own behavior. ```ruby class OrderStatus < EnumerateIt::Base associate_values :pending, :shipped class Pending def next_action 'Review and process' end end class Shipped def next_action 'Track delivery' end end end class Order < ApplicationRecord has_enumeration_for :status, create_helpers: { polymorphic: true } end order = Order.new(status: OrderStatus::PENDING) order.status_object #=> # order.status_object.next_action #=> 'Review and process' order.status = OrderStatus::SHIPPED order.status_object.next_action #=> 'Track delivery' ``` -------------------------------- ### Generated Helper Methods with Prefix Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md Shows how to prefix generated helper methods with the attribute name when `create_helpers: { prefix: true }` is used. This helps avoid naming conflicts in complex models. ```ruby class Order < ApplicationRecord has_enumeration_for :status, create_helpers: { prefix: true } end order = Order.new(status: OrderStatus::PENDING) # Methods are prefixed with attribute name order.status_pending? #=> true order.status_shipped! # Sets and saves ``` -------------------------------- ### Get Enumeration Value from Key Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/base.md Returns the enumeration value for a specific key symbol or string. Returns nil if the key is nil or not found. ```ruby class Status < EnumerateIt::Base associate_values :active, :inactive end Status.value_from_key(:active) ``` -------------------------------- ### Troubleshooting: Method Not Found Error Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/quick-reference.md If you encounter an `undefined method` error for helper methods (e.g., `admin?`), ensure `create_helpers: true` is set when defining the enumeration. ```ruby has_enumeration_for :role, create_helpers: true ``` -------------------------------- ### Get Enumeration Value from Constant Name Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/base.md Returns the enumeration value for a specific uppercase constant name. Returns nil if the constant does not exist. ```ruby class Status < EnumerateIt::Base associate_values :active, :inactive end Status.value_for('ACTIVE') Status.value_for('UNKNOWN') ``` -------------------------------- ### Generated Helper Methods for Enumerations Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md Illustrates the instance methods automatically generated by `create_helpers: true`, including query methods, mutator methods, and humanize/key retrieval. ```ruby class Order < ApplicationRecord has_enumeration_for :status, create_helpers: true end order = Order.new(status: OrderStatus::PENDING) # Query method order.pending? #=> true order.shipped? #=> false # Mutator method (calls save! on ActiveRecord) order.shipped! # Sets status to SHIPPED and saves # Humanize (always created, even without create_helpers) order.status_humanize #=> 'Shipped' # Key retrieval (always created, even without create_helpers) order.status_key #=> :shipped ``` -------------------------------- ### Get Enumeration as Array for Forms Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/base.md The `to_a` method returns an array of `[label, value]` pairs, suitable for use with Rails form helpers. ```ruby class Status < EnumerateIt::Base associate_values :active, :inactive end Status.to_a #=> [['Active', 'active'], ['Inactive', 'inactive']] ``` -------------------------------- ### Troubleshooting: Validation Not Running Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/quick-reference.md Ensure that validation is enabled by default. If invalid values are accepted, check if `skip_validation: true` is used or if `allow_blank` is set inappropriately. ```ruby has_enumeration_for :role # Validation enabled by default ``` -------------------------------- ### Troubleshooting: Custom Helper Override Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/quick-reference.md Avoid overriding built-in helper methods by renaming your custom helpers. For example, change `list` to `my_list`. ```ruby custom_helpers do def my_list(value) # Changed from 'list' # ... end end ``` -------------------------------- ### Define Basic Enumeration Values Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/configuration.md Sets up a basic enumeration with a list of associated values. This is the simplest way to define an enumeration with symbolic names. ```ruby class Status < EnumerateIt::Base associate_values :active, :inactive, :pending end ``` -------------------------------- ### Search Integration with Ransack Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md Demonstrates how Ransack automatically integrates with EnumerateIt scopes for searching. ```ruby class Order < ApplicationRecord has_enumeration_for :status, create_scopes: true # Ransack automatically picks up scopes # Search: status_eq = "pending" end ``` -------------------------------- ### Method Naming Conventions (With Prefix) Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/quick-reference.md Configure EnumerateIt to use a prefix for generated query and mutator methods. This helps avoid naming conflicts. ```ruby has_enumeration_for :role, create_helpers: { prefix: true } # Query methods: {attribute}_{value}? user.role_admin? # Mutator methods: {attribute}_{value}! user.role_admin! ``` -------------------------------- ### Inspecting Enumeration State Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md Shows how to inspect the state and available methods of an enumeration. ```ruby # View all values OrderStatus.list #=> ['pending', 'shipped', ...] # View internal structure OrderStatus.enumeration #=> { pending: ['pending', :pending], ... } # Check what's defined OrderStatus.custom_helper_methods #=> [:completed?, :is_final?] ``` -------------------------------- ### Get Key for Enumeration Value Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/base.md Use `key_for` to retrieve the symbol key associated with a given enumeration value. Returns nil if the value is not found. ```ruby class Status < EnumerateIt::Base associate_values :active, :inactive end Status.key_for('active') #=> :active Status.key_for('unknown') #=> nil ``` -------------------------------- ### Internationalization (I18n) Methods Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/quick-reference.md Demonstrates using I18n methods like `t` for translations and `humanize` for displaying enumerated values in a user-friendly format. Shows how translations are used for both the enumeration class and model attributes. ```ruby Status.t('active') #=> 'Currently Active' Status.translations #=> ['Currently Active', 'Not Active'] user.status_humanize #=> 'Currently Active' ``` -------------------------------- ### Get Humanized Enumeration Label Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/class_methods.md Returns the translated or humanized label for the attribute's current enumeration value. This is useful for displaying user-friendly names. ```ruby person.relationship_status_humanize #=> 'Married' ``` -------------------------------- ### Get Custom Helper Method Names Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/base.md Use `custom_helper_methods` to retrieve an array of symbols representing the names of custom helper methods defined using `custom_helpers`. ```ruby class RelationshipStatus < EnumerateIt::Base associate_values :single, :married custom_helpers do def ever_married?(value) [MARRIED].include?(value) end end end RelationshipStatus.custom_helper_methods #=> [:ever_married?] ``` -------------------------------- ### Generate Basic Enumeration Skeleton Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/rails-generator.md Use this command to create a new enumeration class file without any initial values. You will need to manually add the desired values to the generated file. ```bash rails generate enumerate_it:enum Status ``` -------------------------------- ### Constants Reference Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/quick-reference.md Illustrates how enumeration constants are generated as uppercase versions of their keys. Shows the transformation rule used for generating these constants. ```ruby class Status < EnumerateIt::Base associate_values :active, :inactive, :user_pending end Status::ACTIVE #=> 'active' Status::INACTIVE #=> 'inactive' Status::USER_PENDING #=> 'user_pending' Transformation rule: `key.to_s.tr('-', '_').gsub(/\p{blank}/, '_').upcase` ``` -------------------------------- ### Efficient Querying with Scopes Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md Shows how to efficiently query records using enumeration scopes and WHERE clauses, avoiding loading all records. ```ruby # Good - Uses scope index Order.shipped.count # Good - Uses enumeration in WHERE clause Order.where(status: OrderStatus::SHIPPED).count # Avoid - Loads all records Order.all.select { |o| o.shipped? }.count # Better - Use where clause Order.where(status: [OrderStatus::SHIPPED, OrderStatus::DELIVERED]) ``` -------------------------------- ### Get Enumeration Key Symbol Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/class_methods.md Returns the key symbol for the attribute's current enumeration value. This is useful for internal logic or when working with keys directly. ```ruby person.relationship_status_key #=> :married ``` -------------------------------- ### Tracing Method Calls on Enumerated Objects Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md Demonstrates how to find available methods related to an enumeration on an object and check class associations. ```ruby # See which methods are available order.methods.grep(/status/) #=> [:status, :status=, :status_humanize, :status_key, :pending?, ...] # Check class associations Order.enumerations #=> { status: OrderStatus } ``` -------------------------------- ### Define Enumeration with Naming Variations Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/exported-symbols.md Demonstrates how enumeration constants are generated from keys with dashes, spaces, or no special characters. Hyphens and spaces are converted to underscores. ```ruby associate_values :with_dash, :with_space, :normal # Constants: Status::WITH_DASH #=> 'with_dash' Status::WITH_SPACE #=> 'with_space' Status::NORMAL #=> 'normal' ``` -------------------------------- ### Create Boolean Helper Methods for Enumeration Options Source: https://github.com/lucascaton/enumerate_it/blob/main/README.md Enables the creation of boolean helper methods (e.g., `married?`) for each enumeration constant when `create_helpers: true` is set. ```ruby class Person < ApplicationRecord has_enumeration_for :relationship_status, with: RelationshipStatus, create_helpers: true end p = Person.new p.relationship_status = RelationshipStatus::MARRIED p.married? #=> true p.divorced? #=> false ``` -------------------------------- ### Get Enumeration Values from Constant Names Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/base.md Returns an array of enumeration values corresponding to a list of uppercase constant names. Useful for mapping external identifiers to internal values. ```ruby class Status < EnumerateIt::Base associate_values :active, :inactive end Status.values_for(['ACTIVE', 'INACTIVE']) ``` -------------------------------- ### Access Internal Enumeration Hash Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/api-reference/base.md Use `enumeration` to get the internal hash that maps symbol keys to `[value, key_symbol]` pairs. This provides direct access to the enumeration's internal structure. ```ruby class Status < EnumerateIt::Base associate_values :active, :inactive end Status.enumeration #=> { active: ['active', :active], inactive: ['inactive', :inactive] } ``` -------------------------------- ### Access Custom Class Helper Methods Source: https://github.com/lucascaton/enumerate_it/blob/main/README.md Illustrates how to call custom helper methods defined on the enumeration class. ```ruby RelationshipStatus.ever_married?(RelationshipStatus::MARRIED) #=> true RelationshipStatus.ever_married?(RelationshipStatus::DIVORCED) #=> true RelationshipStatus.ever_married?(RelationshipStatus::SINGLE) #=> false ``` -------------------------------- ### I18n Configuration for Enumerations Source: https://github.com/lucascaton/enumerate_it/blob/main/README.md Configure your locale file to translate enumeration values. Use the 'enumerations..' path for translations. ```yaml # Your locale file pt-BR: enumerations: relationship_status: married: Casado ``` -------------------------------- ### Updating Enumeration Class with Custom Helpers Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/rails-generator.md Modify the enumeration class to add custom helper methods. This example shows how to define a helper to check if a specific value (like moderator) is present. ```ruby class UserRole < EnumerateIt::Base associate_values( :admin, :user, :guest, :moderator # NEW ) custom_helpers do def moderates?(value) value == MODERATOR end end end ``` -------------------------------- ### Migration: Add Enumeration Column to Existing Model Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md Provides a Rails migration example to add a new string column for an enumeration to an existing database table. Includes setting a default value for the new column. ```ruby # Step 1: Create migration # db/migrate/20240101000000_add_status_to_orders.rb class AddStatusToOrders < ActiveRecord::Migration[7.0] def change add_column :orders, :status, :string, default: 'pending' end end ``` -------------------------------- ### Generate Prefixed Helper Methods Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/configuration.md Creates query methods with a prefix derived from the attribute name, useful when multiple enumerations share value names. ```ruby class User < ApplicationRecord has_enumeration_for :role, create_helpers: { prefix: true } has_enumeration_for :status, create_helpers: { prefix: true } end # Creates: role_admin?, role_user?, status_active?, status_inactive? user.role_admin? #=> true/false user.status_active? #=> true/false ``` -------------------------------- ### Generate Enumeration with Basic Attributes Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/rails-generator.md Provide a space-separated list of enumeration values as ATTRIBUTES to populate the generated class. ```bash rails generate enumerate_it:enum Status active inactive pending ``` -------------------------------- ### Create Helpers with Polymorphic Accessor Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/types.md Use `create_helpers: { polymorphic: true }` to generate a polymorphic object accessor with a default `_object` suffix. ```ruby has_enumeration_for :status, create_helpers: { polymorphic: true } ``` -------------------------------- ### Nil Handling for Instance Attributes Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/errors.md Explains that instance methods like `role_humanize` and `role_key` return nil when the attribute itself is nil. ```ruby user.role = nil user.role_humanize #=> nil user.role_key #=> nil ``` -------------------------------- ### Generate Helper Methods for Enumeration Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/configuration.md Enables the creation of query methods (e.g., `admin?`) for each enumeration value. ```ruby class User < ApplicationRecord has_enumeration_for :role, create_helpers: true end # Creates: admin?, user?, guest? methods user.admin? #=> true/false depending on current value ``` -------------------------------- ### Define Non-ActiveRecord Instance with Enumeration Source: https://github.com/lucascaton/enumerate_it/blob/main/README.md Demonstrates how to set up an enumeration for an attribute on a non-ActiveRecord class. ```ruby class Person extend EnumerateIt attr_accessor :relationship_status has_enumeration_for :relationship_status end ``` -------------------------------- ### nil Handling Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/quick-reference.md Demonstrates how EnumerateIt handles `nil` values for enumeration attributes. Methods like `humanize` and `key` return `nil`, and query methods return `false`. ```ruby user.role = nil user.role_humanize #=> nil user.role_key #=> nil user.admin? #=> false Status.key_for(nil) #=> nil ``` -------------------------------- ### Create Scopes with Prefixed Option Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/types.md Use `create_scopes: { prefix: true }` to generate prefixed scopes such as `status_active`. ```ruby has_enumeration_for :status, create_scopes: { prefix: true } ``` -------------------------------- ### Generate Enumeration with Custom Values Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/rails-generator.md Use key:value syntax for ATTRIBUTES to specify custom values for enumeration items, useful for legacy databases. ```bash rails generate enumerate_it:enum Status active:1 inactive:2 pending:3 ``` -------------------------------- ### EnumerateIt::Base Class Methods Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/exported-symbols.md Provides methods for defining, accessing, querying, iterating over, and managing metadata for enumerations. ```APIDOC ## EnumerateIt::Base Class Methods ### Description Provides methods for defining, accessing, querying, iterating over, and managing metadata for enumerations. ### Methods #### Enumeration Definition Methods - **associate_values(*args)**: Defines enumeration values. - **sort_by(sort_mode)**: Configures enumeration sort order. - **custom_helpers(&block)**: Adds custom class methods to the enumeration. #### Data Access Methods - **list**: Returns an Array of all enumeration values. - **keys**: Returns an Array of all enumeration key symbols. - **enumeration**: Returns the internal enumeration hash. - **to_h**: Returns key-value pairs as a Hash. - **to_a**: Returns [label, value] pairs as an Array, suitable for forms. - **to_json(options = nil)**: Returns the JSON representation of the enumeration. - **to_range**: Returns a Range from the minimum to maximum value. - **length**: Returns the count of enumeration values. #### Query Methods - **value_for(key)**: Retrieves the value for a given constant name. Returns nil if not found. - **value_from_key(key)**: Retrieves the value for a given key symbol. Returns nil if not found. - **key_for(value)**: Retrieves the key symbol for a given value. Returns nil if not found. - **values_for(keys)**: Retrieves an Array of values for multiple keys. - **t(value)**: Translates a value to its corresponding label. - **translate(value)**: Translates a value using custom behavior. #### Iteration Methods - **each_value(&block)**: Iterates over each value, yielding it to the block. - **each_key(&block)**: Iterates over each key, yielding it to the block. - **each_translation(&block)**: Iterates over each translation, yielding it to the block. - **translations**: Returns an Array of all translations (labels). #### Metadata Methods - **custom_helper_methods**: Returns an Array of custom helper method names. - **sort_mode**: Returns the configured sort mode (Symbol or nil). ``` -------------------------------- ### I18n Translations for Namespaced Enumerations Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/types.md For namespaced enumerations like `Design::Color`, use forward slash notation in the locale file keys. ```yaml en: enumerations: "design/color": blue: Blue red: Red ``` -------------------------------- ### Require Specific EnumerateIt Classes Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/exported-symbols.md Shows how to require specific internal classes of the EnumerateIt gem, although requiring the main gem is generally sufficient. ```ruby # Specific classes (not needed, above covers all) require 'enumerate_it/base' require 'enumerate_it/class_methods' ``` -------------------------------- ### EnumerateIt Module Methods Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/exported-symbols.md Provides methods for extending classes to gain enumeration capabilities. ```APIDOC ## EnumerateIt Module Methods ### Description Provides methods for extending classes to gain enumeration capabilities. ### Methods - **extended(receiver)**: Extends the `receiver` class with enumeration support, setting up the `enumerations` class attribute and including `ClassMethods`. ### Usage ```ruby # Rails (automatic) class User < ApplicationRecord has_enumeration_for :status end # Non-Rails (manual) class User extend EnumerateIt has_enumeration_for :status end ``` ``` -------------------------------- ### Troubleshooting: Constant Not Found Error Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/quick-reference.md If you receive an `uninitialized constant` error, explicitly specify the enumeration class using the `with:` option. ```ruby has_enumeration_for :role, with: UserRole ``` -------------------------------- ### String Values Persistence Strategy Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md The default and recommended strategy for persisting enumeration values as strings in the database. This approach offers readability and self-documentation. ```ruby class Status < EnumerateIt::Base associate_values :active, :inactive end # In database: 'active', 'inactive' ``` -------------------------------- ### Empty Values Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/quick-reference.md Shows how to handle empty lists when retrieving values or iterating through enumerations. `values_for` returns an empty array, and iteration methods do nothing. ```ruby empty_list = [] Status.values_for(empty_list) #=> [] # Calling with no blocks Status.each_value { } Status.each_translation { } ``` -------------------------------- ### Enumeration Lookup Performance Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/implementation-guide.md Direct constant access provides the fastest (O(1)) lookup performance for enumeration values. ```ruby # O(1) - Direct constant access (fastest) value = OrderStatus::PENDING ``` -------------------------------- ### Create Helpers with Polymorphic Accessor and Custom Suffix Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/types.md Configure `polymorphic: { suffix: '_mode' }` within `create_helpers` to specify a custom suffix for the polymorphic object accessor. ```ruby has_enumeration_for :status, create_helpers: { polymorphic: { suffix: '_mode' } } ``` -------------------------------- ### Accessing Legacy Database Associated Values Source: https://github.com/lucascaton/enumerate_it/blob/main/README.md Demonstrates how to access the associated legacy database value from an enumeration constant. ```ruby RelationshipStatus::MARRIED #=> 2 ``` -------------------------------- ### Generator Help Output Source: https://github.com/lucascaton/enumerate_it/blob/main/_autodocs/rails-generator.md This output details the usage of the `rails generate enumerate_it:enum` command, including its arguments and available options like language and singular name. ```text Usage: rails generate enumerate_it:enum NAME [ATTRIBUTES] [options] Options: [--lang=LANG] # Language to use in i18n # Default: en [--singular=SING] # Singular name for i18n # Default: en ```