### YAML with Aliases Example Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-file-sources.md Illustrates how to use YAML aliases for code reuse. Alias containers are defined using keys starting with '/'. ```yaml /aliases: soda_flavor: &soda_flavor sweet soda_price: &soda_price 1.0 - id: 1 name: Coke flavor: *soda_flavor price: *soda_price ``` -------------------------------- ### Complete Model and Data File Example Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-file-sources.md Defines a `Country` model with fields and specifies a root path and filename for its data. Includes example YAML data and usage patterns. ```ruby # app/models/country.rb class Country < ActiveYaml::Base field :name field :code field :continent set_root_path Rails.root.join("config/data") set_filename "countries" end # config/data/countries.yml - id: 1 name: US code: US continent: North America - id: 2 name: Canada code: CA continent: North America # Usage Country.first # => # Country.find_by_code("CA") # => # Country.where(continent: 'North America').count # => 2 # In controller before_action { Country.reload(true) if Rails.env.development? } ``` -------------------------------- ### Install ActiveHash Manually Source: https://github.com/active-hash/active_hash/blob/master/README.md Install ActiveHash using the gem command if not using Bundler. ```ruby gem install active_hash ``` -------------------------------- ### Install ActiveHash with Bundler Source: https://github.com/active-hash/active_hash/blob/master/README.md Add this line to your application's Gemfile to install ActiveHash. ```ruby gem 'active_hash' ``` -------------------------------- ### YAML File Format: Array Style Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-file-sources.md Example of a YAML file structured as an array of hashes. ```yaml - id: 1 name: US code: US - id: 2 name: Canada code: CA ``` -------------------------------- ### Ruby Code Example Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/README.md Demonstrates a basic usage of Active Hash to find a record by its ID. ```ruby # Ruby code showing usage Country.find(1) ``` -------------------------------- ### Complete ActiveHash Association Example Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-associations.md Illustrates defining and using 'has_many' and 'belongs_to' associations between two ActiveHash models. Includes data setup and usage examples for retrieving associated records. ```ruby # Define models class Country < ActiveHash::Base include ActiveHash::Associations has_many :cities self.data = [ {:id => 1, :name => "US"}, {:id => 2, :name => "Canada"} ] end class City < ActiveHash::Base include ActiveHash::Associations belongs_to :country self.data = [ {:id => 1, :country_id => 1, :name => "New York"}, {:id => 2, :country_id => 1, :name => "Los Angeles"}, {:id => 3, :country_id => 2, :name => "Toronto"} ] end # Usage us = Country.find(1) us.cities # => # (3 records: NY, LA, Toronto filtered) # Actually yields: NY, LA (country_id == 1) city = City.find(1) city.country # => # city.country = Country.find(2) city.country_id # => 2 ``` -------------------------------- ### Complete Active Hash Model Configuration Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/configuration.md A full example showing how to define an Active Hash model, including associations, fields with defaults, setting the root path and filename for data, enum accessors, scopes, and initial data. Also includes Rails initializer configuration for development environments. ```ruby # app/models/country.rb class Country < ActiveYaml::Base include ActiveHash::Associations include ActiveHash::Enum has_many :cities field :name field :code field :continent field :language, :default => 'English' set_root_path "#{Rails.root}/config/data" set_filename "countries" enum_accessor :code scope :english_speaking, -> { where(language: 'English') } scope :in_continent, ->(c) { where(continent: c) } end ``` ```yaml # config/data/countries.yml - id: 1 code: US name: United States continent: North America language: English - id: 2 code: CA name: Canada continent: North America language: English - id: 3 code: MX name: Mexico continent: North America language: Spanish ``` ```ruby # config/initializers/active_hash.rb Rails.application.config.to_prepare do Country.reload(true) if Rails.env.development? end ``` ```ruby # Usage Country.english_speaking.in_continent('North America') Country::US.language ``` -------------------------------- ### YAML File Format: Hash Style Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-file-sources.md Example of a YAML file structured as a hash. The keys are automatically added as a 'key' attribute to the model instances. ```yaml us: id: 1 name: US code: US canada: id: 2 name: Canada code: CA ``` -------------------------------- ### Configure ActiveYaml Root Path and Filename Source: https://github.com/active-hash/active_hash/blob/master/README.md Customize the directory and filename ActiveYaml searches for by using set_root_path and set_filename. This example configures it to look for '/u/data/sample.yml'. ```ruby class Country < ActiveYaml::Base set_root_path "/u/data" set_filename "sample" end ``` -------------------------------- ### ActiveYaml Aliases in YAML (Hash Style) Source: https://github.com/active-hash/active_hash/blob/master/README.md This example demonstrates using YAML aliases with ActiveYaml::Aliases in a hash-style YAML file. Aliases defined under a '/aliases' key can be referenced throughout the file. ```yaml # Key style /aliases: soda_flavor: &soda_flavor sweet soda_price: &soda_price 1.0 coke: id: 1 name: Coke flavor: *soda_flavor price: *soda_price ``` -------------------------------- ### ActiveJSON Data Format: Hash Style Source: https://github.com/active-hash/active_hash/blob/master/README.md Example of JSON data structured as a hash for ActiveJSON. Note: The provided example has a syntax error and is presented as is. ```json { { "us": { "id": 1, "name": "US", "custom_field_1": "value1" } }, { "canada": { "id": 2, "name": "Canada", "custom_field_2": "value2" } } } ``` -------------------------------- ### I18n Configuration for ActiveHash Source: https://github.com/active-hash/active_hash/blob/master/README.md Example of how to configure internationalization for ActiveHash models by adding translations to a locale file. ```yaml ja: activemodel: models: # `Country.model_name.human` will evaluates to "国" country: "国" ``` -------------------------------- ### JSON File Format: Array Style Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-file-sources.md Example of a JSON file structured as an array of objects, which ActiveJSON::Base can load. ```APIDOC ### JSON File Format: Array Style ```json [ { "id": 1, "name": "US", "code": "US" }, { "id": 2, "name": "Canada", "code": "CA" } ] ``` ``` -------------------------------- ### ActiveYaml Aliases in YAML (Array Style) Source: https://github.com/active-hash/active_hash/blob/master/README.md Include ActiveYaml::Aliases to use YAML aliases. Keys starting with '/' are ignored and can be used to define reusable alias blocks. This example shows alias usage in array-style YAML. ```yaml # Array Style - /aliases: soda_flavor: &soda_flavor sweet soda_price: &soda_price 1.0 - id: 1 name: Coke flavor: *soda_flavor price: *soda_price ``` -------------------------------- ### Custom File Loader Implementation Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-file-sources.md Example of creating a custom file loader by extending ActiveFile::Base. This involves overriding `extension` to specify the file type (e.g., 'csv') and `load_file` to parse the file content into an Array of Hashes. ```ruby class Country < ActiveFile::Base set_root_path "/app/config" set_filename "countries" class << self def extension "csv" end def load_file # load_file must return Array of Hashes CSV.read(full_path, headers: true).map(&:to_h) end end end # Requirements: # - Override `load_file` to return Array # - Override `extension` to specify file type # - `full_path` is available for use # Source: lib/active_file/base.rb ``` -------------------------------- ### JSON File Format: Hash/Object Style Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-file-sources.md Example of a JSON file structured as a hash/object, which ActiveJSON::Base can load. It also demonstrates how the keys become attributes. ```APIDOC ### JSON File Format: Hash/Object Style ```json { "us": { "id": 1, "name": "US", "code": "US" }, "canada": { "id": 2, "name": "Canada", "code": "CA" } } ``` **Automatic Key Attribute:** Like ActiveYaml, the key becomes an attribute. ```ruby Country.find(1).key # => "us" ``` ``` -------------------------------- ### YAML with ERB Example Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-file-sources.md Shows how to embed Ruby code within a YAML file using ERB for dynamic data generation. ```yaml - id: 1 name: US email: <%= "contact@#{Time.now.year}.com" %> password: <%= ENV['COUNTRY_PASSWORD'] %> ``` -------------------------------- ### Common Instance Methods in ActiveHash Source: https://github.com/active-hash/active_hash/blob/master/README.md Provides examples of common instance methods for ActiveHash objects, similar to ActiveRecord. These include methods for accessing and modifying attributes, checking record status, and hashing. ```ruby Country#id # => returns the id or nil Country#id= # => sets the id attribute Country#quoted_id # => returns the numeric id Country#to_param # => returns the id as a string Country#new_record? # => returns true if is not part of Country.all, false otherwise Country#readonly? # => true Country#hash # => the hash of the id (or the hash of nil) Country#eql? # => compares type and id, returns false if id is nil ``` -------------------------------- ### API Reference Method Documentation Format Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/INDEX.md This is a template illustrating the standard format for documenting individual methods within the API reference. It includes sections for description, code examples, parameters, return values, side effects, raised errors, and source code location. ```markdown ## method_name Description of what the method does. Code example showing typical usage. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | name | String | yes | — | What it does | **Returns:** Return type and meaning **Side Effects:** Any mutations **Raises:** Errors and conditions **Source:** lib/path/to/file.rb:line_number ``` -------------------------------- ### Get first record(s) Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-relation.md Use `first` to retrieve the first record or an array of the first few records from the relation. ```ruby Country.all.first # => # ``` ```ruby Country.all.first(2) # => [#, #] ``` -------------------------------- ### Handle ReservedFieldError Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/errors.md Demonstrates how to rescue ReservedFieldError and provides examples of alternative field names that can be used instead of reserved ones. ```ruby begin class Country < ActiveHash::Base field :attributes # BAD end rescue ActiveHash::ReservedFieldError => e puts e.message # Use a different field name class Country < ActiveHash::Base field :attrs field :attr_list field :attribute_data end end ``` -------------------------------- ### Get Next Available ID Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/errors.md Demonstrates how to retrieve the next available numeric ID using `Country.next_id` and how `Country.create` automatically assigns this ID. ```ruby class Country < ActiveHash::Base end Country.data = [ {:id => 1, :name => "US"}, {:id => 2, :name => "Canada"} ] next_id = Country.next_id # => 3 (next numeric ID) country = Country.create(id: next_id, name: "Mexico") # or let it auto-increment country = Country.create(name: "Mexico") # => id is auto-assigned as 3 ``` -------------------------------- ### Customizing ActiveFile Loading and Extension Source: https://github.com/active-hash/active_hash/blob/master/README.md Define a custom load_file method and file extension for ActiveFile. This example uses a 'super_secret' extension and a custom decoder. ```ruby class Country < ActiveFile::Base set_root_path "/u/data" set_filename "sample" class << self def extension "super_secret" end def load_file MyAwesomeDecoder.load_file(full_path) end end end ``` -------------------------------- ### Customizing ActiveJSON Path and Filename Source: https://github.com/active-hash/active_hash/blob/master/README.md Specify a custom root path and filename for ActiveJSON. The example sets the path to '/u/data' and the filename to 'sample', looking for '/u/data/sample.json'. ```ruby class Country < ActiveJSON::Base set_root_path "/u/data" set_filename "sample" end ``` -------------------------------- ### ActiveFile::Base.extension Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-file-sources.md This method should be overridden by subclasses to specify the file extension to be used for loading data. For example, 'yml' for YAML files. ```APIDOC ## ActiveFile::Base.extension ### Description Override this method to specify file extension. ### Method Class Method ### Response #### Success Response (String) Returns the file extension as a String. ### Must Override Yes, raises "Override Me" if not implemented ### Source `lib/active_file/base.rb:42` ``` -------------------------------- ### Configuring Root Path and Filename in ActiveJSON::Base Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-file-sources.md Configures the root path and filename for ActiveJSON::Base. This example sets the root path to '/app/data' and the filename to 'countries', causing it to look for '/app/data/countries.json'. ```ruby class Country < ActiveJSON::Base set_root_path "/app/data" set_filename "countries" end # Looks for /app/data/countries.json ``` -------------------------------- ### Combine Query Conditions Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/quick-reference.md Chain multiple query methods like `.where`, `.order`, and `.first` to build complex queries. This example filters by continent, orders by name, and retrieves the first record. ```ruby Country.where(continent: 'NA').order(name: :asc).first ``` -------------------------------- ### Define Data within a Class Source: https://github.com/active-hash/active_hash/blob/master/README.md Load data into an ActiveHash model. This example shows defining data directly within the application's initializer. ```ruby # app/models/country.rb class Country < ActiveHash::Base end # config/initializers/data.rb Rails.application.config.to_prepare do Country.data = [ {:id => 1, :name => "US"}, {:id => 2, :name => "Canada"} ] end ``` -------------------------------- ### Multiple Field Example for Uniqueness Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/errors.md Illustrates using multiple fields with enum_accessor to ensure unique constant names, such as combining 'name' and 'state' to create unique identifiers. ```ruby class Town < ActiveHash::Base include ActiveHash::Enum # Use multiple fields to ensure uniqueness # Constant will be NAME_STATE enum_accessor :name, :state self.data = [ {:id => 1, :name => "Springfield", :state => "NY"}, {:id => 2, :name => "Springfield", :state => "OH"} ] # Safe: SPRINGFIELD_NY and SPRINGFIELD_OH are unique end ``` -------------------------------- ### Configure Multiple File Loading Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/quick-reference.md Enable loading from multiple files by calling `use_multiple_files` and then specifying the filenames. This consolidates data from various sources. ```ruby use_multiple_files set_filenames "file1", "file2" ``` -------------------------------- ### id Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-base.md Gets the unique identifier for the record. ```APIDOC ## id ### Description Get the record's id. ### Method `id` ### Request Example ```ruby country.id # => 1 ``` ### Returns Object or nil ``` -------------------------------- ### Get Record ID Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-base.md Retrieve the unique identifier for the record. ```ruby country.id # => 1 ``` -------------------------------- ### Create and Save Records Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/quick-reference.md Use `create` to instantiate and save a new record. `create!` raises an error if validation fails. `add` is an alias for `create`. Use `new` followed by `save` for separate operations. `insert` bypasses validations. ```ruby # Create and save country = Country.create(:id => 1, :name => "Brazil") country = Country.create(name: "Brazil") # ID auto-increments # Create with validation (always true) country = Country.create!(:id => 1, :name => "Brazil") # Add (alias for create) Country.add(:id => 1, :name => "Brazil") # New and save separately country = Country.new(:name => "Brazil") country.save # => true # Insert directly country = Country.new(:id => 1, :name => "Brazil") Country.insert(country) # Via associations country = Country.find(1) city = City.new(:id => 1, :country_id => 1, :name => "NYC") Country.cities << city ``` -------------------------------- ### Get Field Names Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-base.md Returns an array of all defined field names, excluding the 'id' field. ```ruby class Country < ActiveHash::Base fields :name, :code end Country.field_names # => [:name, :code] ``` -------------------------------- ### Initialize a New Country Instance Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-base.md Create a new instance with attributes. The 'id' can be auto-assigned on save if not provided. A block can also be used for configuration. ```ruby country = Country.new(:id => 3, :name => "Mexico") country = Country.new(:name => "Mexico") # id auto-assigned on save country = Country.new { |c| c.name = "Mexico" } # block form ``` -------------------------------- ### ActiveJSON Data Format: Array Style Source: https://github.com/active-hash/active_hash/blob/master/README.md Example of JSON data structured as an array of hashes for ActiveJSON. ```json [ { "id": 1, "name": "US", "custom_field_1": "value1" }, { "id": 2, "name": "Canada", "custom_field_2": "value2" } ] ``` -------------------------------- ### Get Cache Key Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-base.md Generate a string representing the cache key for the record, typically in the format 'model_name/id'. ```ruby country = Country.find(1) country.cache_key # => "countries/1" ``` -------------------------------- ### initialize Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-base.md Creates a new ActiveHash instance with specified attributes or using a block for configuration. Attributes can be provided as a Hash, and an ID can be auto-assigned on save if not provided. ```APIDOC ## initialize ### Description Create a new instance with attributes. ### Method `initialize` ### Parameters #### Attributes - **attributes** (Hash) - Optional - Initial attribute values - **block** (Proc) - Optional - Optional block to configure instance ### Request Example ```ruby country = Country.new(:id => 3, :name => "Mexico") country = Country.new(:name => "Mexico") # id auto-assigned on save country = Country.new { |c| c.name = "Mexico" } # block form ``` ### Returns Record instance ``` -------------------------------- ### Setting Data Flow Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/module-overview.md Illustrates the process of setting data for an Active Hash model, including marking the data as dirty, auto-assigning fields, and inserting records into the in-memory store. ```text Class.data = [hash1, hash2, ...] ↓ mark_dirty() ↓ auto_assign_fields() — Define fields from hash keys ↓ insert() for each hash — Add to in-memory store ↓ update record_index — Hash for fast ID lookups ``` -------------------------------- ### Get Class Cache Key Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-base.md Retrieves the cache key for the class, typically 'countries' if ActiveModel is available. ```ruby Country.cache_key # => "countries" (if ActiveModel available) ``` -------------------------------- ### Custom File Formats with ActiveFile::Base Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-file-sources.md Instructions on how to create custom file loaders by extending ActiveFile::Base, overriding `load_file` and `extension` methods. ```APIDOC ## Custom File Formats Create custom file loaders by extending ActiveFile::Base. ```ruby class Country < ActiveFile::Base set_root_path "/app/config" set_filename "countries" class << self def extension "csv" end def load_file # load_file must return Array of Hashes CSV.read(full_path, headers: true).map(&:to_h) end end end ``` **Requirements:** - Override `load_file` to return Array - Override `extension` to specify file type - `full_path` is available for use **Source:** `lib/active_file/base.rb` ``` -------------------------------- ### Get Column Names as Strings Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-base.md Retrieves an array of all column names as strings, suitable for CSV exports. ```ruby class Country < ActiveHash::Base fields :name, :code end Country.column_names # => ["id", "name", "code"] ``` -------------------------------- ### ActiveHash::Base Class and Instance Methods Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/README.md Documentation for the ActiveHash::Base class, covering class methods like field, fields, data=, all, where, find, find_by, create, insert, delete_all, and instance methods such as id, attributes, save, new_record?, and persisted?. It also details dynamic field access and the error catalog. ```APIDOC ## ActiveHash::Base Class and Instance Methods ### Description Provides the core functionality for defining and interacting with ActiveHash models. Covers class methods for data management and querying, as well as instance methods for record manipulation and attribute access. ### Class Methods - **field(name, type, options = {})**: Defines a field for the model. - **fields**: Returns a hash of all defined fields. - **data=(data)**: Sets the raw data for the model. - **all**: Retrieves all records. - **where(conditions = {})**: Filters records based on conditions. - **find(id)**: Finds a record by its ID. - **find_by(attributes = {})**: Finds the first record matching the given attributes. - **create(attributes = {})**: Creates a new record. - **insert(attributes = {})**: Inserts a new record without callbacks. - **delete_all**: Deletes all records. ### Instance Methods - **id**: Returns the record's ID. - **attributes**: Returns a hash of the record's attributes. - **save**: Saves the record. - **new_record?**: Returns true if the record is new. - **persisted?**: Returns true if the record is persisted. ### Dynamic Methods - Dynamic methods for field access (e.g., `record.field_name`). ### Error Catalog - References the error catalog for potential exceptions. ``` -------------------------------- ### Get Primary Key Field Name Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-base.md Retrieves the name of the primary key field, which is always 'id'. ```ruby Country.primary_key # => "id" ``` -------------------------------- ### Get First Record Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-base.md Retrieves the first record from the dataset. Can be used on the entire collection or a filtered subset. ```ruby Country.first # => #1, :name=>"US"}> Country.where(name: 'Canada').first # => #2, :name=>"Canada"}> ``` -------------------------------- ### Define and Use ActiveHash Models Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-base.md Shows how to define a simple ActiveHash model with fields, set data, and perform various query operations. Includes creating new records and using dynamic scopes. ```ruby # Define a simple model class Country < ActiveHash::Base field :name field :code field :language, :default => 'English' end # Set data Country.data = [ {:id => 1, :name => "US", :code => "US"}, {:id => 2, :name => "Canada", :code => "CA"}, {:id => 3, :name => "Mexico", :code => "MX"} ] # Query records Country.count # => 3 Country.first # => # Country.find(2) # => # Country.find_by_code("CA") # => # Country.where(name: /Can/) # => # Country.order(name: :asc).pluck(:name) # => ["Canada", "Mexico", "US"] # Create new record country = Country.new(:id => 4, :name => "Brazil") country.save Country.count # => 4 # Create with create method Country.create(:id => 5, :name => "Argentina") # Dynamic scopes class Country < ActiveHash::Base scope :north_american, -> { where(id: [1, 2, 3]) } end Country.north_american # => # ``` -------------------------------- ### Get number of records Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-relation.md Use `length` to retrieve the total count of records in the relation. This is an alias for `size`. ```ruby Country.all.length # => 3 ``` -------------------------------- ### Get last record(s) Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-relation.md Use `last` to retrieve the last record or an array of the last few records from the relation. ```ruby Country.all.last # => # ``` -------------------------------- ### Enable Loading from Multiple Files Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-file-sources.md Configures the model to load data from multiple files instead of a single file. This is typically used with `set_filenames`. ```ruby class Country < ActiveYaml::Base use_multiple_files set_filenames "europe", "asia", "americas" end # Will load countries/europe.yml, countries/asia.yml, countries/americas.yml ``` -------------------------------- ### Chaining Relation Queries Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-relation.md Demonstrates how to chain multiple relation methods to build complex queries. All methods return a Relation object, enabling sequential filtering, ordering, and data extraction. ```ruby # All methods return Relation, allowing chaining countries = Country.all .where(continent: 'North America') .where(language: 'English') .order(name: :asc) .pluck(:name) # => ["Canada", "US"] # Can build complex queries results = Country.all .where(population: 1_000_000..500_000_000) .order(population: :desc) .first(5) ``` -------------------------------- ### Preventing DuplicateEnumAccessor with Validation Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/errors.md This example shows how to validate field uniqueness before inserting a record to prevent the DuplicateEnumAccessor error. ```ruby # Validate before inserting class Country < ActiveHash::Base include ActiveHash::Enum enum_accessor :code # Use unique fields end def add_country(name, code) # Ensure code is unique before insertion if Country.find_by_code(code) raise "Code already exists" end country = Country.new(id: Country.next_id, name: name, code: code) Country.insert(country) end ``` -------------------------------- ### Get All Attributes Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-base.md Retrieve all attributes of a record as a hash, with defaults merged in. The returned hash is frozen if defaults exist. ```ruby country = Country.new(:id => 1, :name => "US") country.attributes # => {:id => 1, :name => "US"} ``` -------------------------------- ### Get Last Record Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-base.md Retrieves the last record from the dataset. Useful for accessing the most recently added or sorted record. ```ruby Country.last # => #2, :name=>"Canada"}> ``` -------------------------------- ### File Loading Data Flow Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/module-overview.md Explains the process of loading data from a file in Active Hash, including checking if data is already loaded, reloading if necessary, and parsing the file content. ```text Class.all (or any query) ↓ Check data_loaded? ↓ If false, reload() via thread-safe Mutex ↓ load_file() — Read and parse file ↓ Set self.data (triggers insert) ↓ Mark data_loaded = true ↓ Proceed with query ``` -------------------------------- ### Extract all id values from records Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-relation.md Use `ids` to get an array containing only the `id` values of all records in the relation. ```ruby Country.all.ids # => [1, 2, 3] ``` ```ruby Country.where(language: 'English').ids # => [1, 2] ``` -------------------------------- ### Initialize Model with Array of Hashes Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/types.md Set the data for a model using an Array of Ruby Hashes. Each Hash in the array represents a record and should have consistent keys. ```ruby data = [ {:id => 1, :name => "US"}, {:id => 2, :name => "Canada"} ] Country.data = data ``` -------------------------------- ### Thread-Safe File Loading with Mutex Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/configuration.md Demonstrates how multiple threads can safely read and query data. File loading operations are protected by a mutex to prevent race conditions. ```ruby # Multiple threads can safely read/query Thread.new { Country.all } Thread.new { Country.find(1) } Thread.new { Country.reload(true) } ``` -------------------------------- ### Handling RecordNotFound in a Controller Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/errors.md Example of how to handle ActiveHash::RecordNotFound within a Rails controller action to render a specific response. ```ruby # In controller (rails pattern) def show @country = Country.find(params[:id]) rescue ActiveHash::RecordNotFound render :not_found, status: :not_found end ``` -------------------------------- ### add Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-base.md Alias for the `create` method. Creates and saves a new record with the provided attributes. ```APIDOC ## add ### Description Alias for create. Create and save a new record. ### Method POST ### Endpoint /add ### Parameters #### Request Body - **attributes** (Hash) - Optional - Initial attribute values ### Response #### Success Response (200) - **Record** (Object) - The newly created and saved record. ``` -------------------------------- ### Access All Records and Count Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/quick-reference.md Retrieve all records as a `Relation` object using `.all` or get the total count using `.count`. ```ruby Country.all # All records as Relation Country.count # => Integer ``` -------------------------------- ### ActiveJSON::Base Class Methods: set_root_path, set_filename Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-file-sources.md Shows how to customize the file path and name using `set_root_path` and `set_filename` class methods, similar to ActiveYaml. ```APIDOC ### Class Methods #### set_root_path, set_filename Same as ActiveYaml (inherited). ```ruby class Country < ActiveJSON::Base set_root_path "/app/data" set_filename "countries" end # Looks for /app/data/countries.json ``` ``` -------------------------------- ### Basic Class Data Configuration Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/configuration.md Configure the data source for an ActiveHash class by assigning an array of hashes to `self.data`. ```ruby class Country < ActiveHash::Base self.data = [ {:id => 1, :name => "US"}, {:id => 2, :name => "Canada"} ] end ``` -------------------------------- ### Get Record Hash Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-base.md Generate a hash value for the record, typically based on its ID. This is useful for using records in hash-based collections. ```ruby country = Country.find(1) country.hash # => 1 (same as 1.hash) ``` -------------------------------- ### File-Backed Models Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/README.md Details how to create ActiveHash models backed by files, supporting custom formats, YAML, and JSON. Covers configuration options like `set_root_path`, `set_filename`, and `set_filenames`, as well as ERB processing and YAML alias support. ```APIDOC ## File-Backed Models ### Description Enables models to be persisted and loaded from files, supporting various formats including YAML and JSON. Provides configuration for file paths, names, and processing. ### Base Classes - **ActiveFile::Base**: Base class for custom file format implementations. - **ActiveYaml::Base**: Base class for models backed by YAML files. - **ActiveJSON::Base**: Base class for models backed by JSON files. ### Configuration - **set_root_path(path)**: Sets the root directory for data files. - **set_filename(filename)**: Sets the primary filename for the model's data. - **set_filenames(*filenames)**: Sets multiple filenames to load data from. ### Features - **Custom Format Implementation**: Ability to define and use custom file formats. - **ERB Processing in YAML**: Supports ERB templating within YAML files. - **YAML Alias Support**: Leverages YAML's alias feature for data reuse. - **Multiple File Support**: Can load data from multiple specified files. - **Reloading and Thread Safety**: Mechanisms for reloading data and ensuring thread safety. ``` -------------------------------- ### Create and Save New Record (Raise on Failure) Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-base.md Similar to `create`, but designed to raise an error if the creation fails. Note: In ActiveHash, this method always succeeds. ```ruby country = Country.create!(:id => 3, :name => "Mexico") ``` -------------------------------- ### Count Records Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-base.md Counts the total number of records or the number of records matching a specific condition. Useful for getting aggregate data. ```ruby Country.count # => 2 Country.where(name: 'US').count # => 1 ``` -------------------------------- ### Configure ActiveYaml Base Path and Filename Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/configuration.md Sets the directory and filename for ActiveYaml data files. Assumes a YAML file located at config/data/countries.yml. ```ruby class Country < ActiveYaml::Base set_root_path "#{Rails.root}/config/data" set_filename "countries" end # Looks for: config/data/countries.yml ``` -------------------------------- ### Get a random record from the relation Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-relation.md Use `sample` to retrieve a single random record from the relation. Returns `nil` if the relation is empty. ```ruby Country.all.sample # => # ``` -------------------------------- ### Global belongs_to_active_hash setup Source: https://github.com/active-hash/active_hash/blob/master/README.md Extends `ActiveRecord::Base` globally to allow all ActiveRecord models to use `belongs_to_active_hash` for associations with ActiveHash models. ```ruby ActiveRecord::Base.extend ActiveHash::Associations::ActiveRecordExtensions class Country < ActiveHash::Base end class Person < ActiveRecord::Base belongs_to_active_hash :country end ``` -------------------------------- ### Dynamic Finder Methods Source: https://github.com/active-hash/active_hash/blob/master/README.md Leverage dynamic finder methods based on defined fields for quick data retrieval. ```ruby Country.find_by_name "foo" # => returns the first object matching that name Country.find_all_by_name "foo" # => returns an array of the objects with matching names Country.find_by_id_and_name 1, "Germany" # => returns the first object matching that id and name Country.find_all_by_id_and_name 1, "Germany" # => returns an array of objects matching that name and id ``` -------------------------------- ### Auto-Define Fields from Data Source: https://github.com/active-hash/active_hash/blob/master/README.md ActiveHash automatically defines methods for fields present in the data. This example shows fields being defined after `CustomField.all` is called. ```ruby class CustomField < ActiveHash::Base self.data = [ {:custom_field_1 => "foo"}, {:custom_field_2 => "foo"}, {:custom_field_3 => "foo"} ] end ``` -------------------------------- ### Get All Records Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-base.md Retrieves a chainable ActiveHash::Relation containing all records in the class. This relation can be further filtered or manipulated using methods like `first`. ```ruby Country.all # => # Country.all.first # => #1, :name=>"US"}> ``` -------------------------------- ### Querying Data Flow Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/module-overview.md Details the steps involved in querying data using Active Hash, from creating a Relation with conditions and order to applying filters and sorting to return the final array of records. ```text Model.where(conditions) ↓ Creates Relation with conditions ↓ Model.order(fields) ↓ Appends order_values to Relation ↓ Relation.records (lazy) ↓ apply_conditions() — Filter with Condition matching ↓ apply_order_values() — Sort by fields ↓ Returns Array of matching Records ``` -------------------------------- ### ActiveHash Documentation File Structure Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/MANIFEST.md This snippet shows the directory structure and file names for the 12 comprehensive markdown documentation files generated for the ActiveHash library. It includes line counts for each file. ```text /workspace/home/output/ ├── INDEX.md (269 lines) — Navigation and quick index ├── README.md (392 lines) — Documentation overview and guide ├── MANIFEST.md (this file) — File manifest and structure │ ├── api-reference-base.md (1018 lines) — Core ActiveHash::Base class ├── api-reference-relation.md (722 lines) — Query interface (Relation) ├── api-reference-associations.md (381 lines) — Relationships (has_many, belongs_to) ├── api-reference-file-sources.md (592 lines) — File-backed models (YAML/JSON) ├── api-reference-enum.md (426 lines) — Enum functionality │ ├── types.md (566 lines) — Type definitions and structures ├── errors.md (535 lines) — Error catalog and handling ├── configuration.md (657 lines) — Configuration options and setup ├── module-overview.md (633 lines) — Architecture and design └── quick-reference.md (565 lines) — Quick lookup tables and patterns Total: 6,756 lines of technical documentation Size: 168 KB Files: 12 markdown documents ``` -------------------------------- ### Get Raw Data Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-base.md Retrieves the underlying array of hashes used to populate the ActiveHash class. Use this to inspect the raw data source. ```ruby Country.data # => [{:id => 1, :name => "US"}, {:id => 2, :name => "Canada"}] ``` -------------------------------- ### Count records in relation Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-relation.md Use `count` to get the total number of records in a relation. An optional block can be provided for custom counting logic. ```ruby Country.all.count # => 3 ``` ```ruby Country.where(language: 'English').count # => 2 ``` ```ruby Country.all.count { |c| c.name.length > 5 } # => 1 (with block) ``` -------------------------------- ### Load Data from Multiple Files Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/quick-reference.md Configure a model to load data from multiple YAML files. Specify all filenames to consolidate data from various sources into a single model. ```ruby class Country < ActiveYaml::Base use_multiple_files set_filenames "europe", "asia", "americas" end # Loads: europe.yml, asia.yml, americas.yml ``` -------------------------------- ### Alternative: ActiveRecord with Static Array Source: https://github.com/active-hash/active_hash/blob/master/README.md Shows a traditional ActiveRecord approach using a static array for comparison, before ActiveHash was available. ```ruby # in app/models/person.rb class Person < ActiveRecord::Base COUNTRIES = ["US", "Canada"] end # in some view <%= collection_select :person, :country_id, Person::COUNTRIES, :to_s, :to_s %> ``` -------------------------------- ### Managing In-Memory Records with ActiveHash Source: https://github.com/active-hash/active_hash/blob/master/README.md Illustrates how to manage in-memory records using ActiveHash. This includes creating new records, saving them, and observing the auto-incrementing ID behavior. ```ruby Country.all => # Country.create => #1}> Country.all => #1}>], @conditions=[..], @records_dirty=false> country = Country.new => # country.new_record? => true country.save => true country.new_record? # => false Country.all => #1}>, #2}>], @conditions=[..], @records_dirty=false> ``` -------------------------------- ### Load Data from YAML File Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/quick-reference.md Configure a model to load its data from a specified YAML file. Ensure the root path and filename are correctly set for the data to be loaded. ```ruby class Country < ActiveYaml::Base set_root_path "#{Rails.root}/data" set_filename "countries" end # Loads: data/countries.yml ``` -------------------------------- ### Initialize Model with Hash Data Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/types.md Set the raw data for a model using a single Ruby Hash. The Hash must contain at least an :id key. ```ruby data = {:id => 1, :name => "US", :code => "US"} Country.data = data ``` -------------------------------- ### Lazy Loading for File-Based Active Hash Models Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/configuration.md File-based Active Hash models load their data on the first query, improving application boot time. This is useful when not all data is immediately required. ```ruby class Country < ActiveYaml::Base end # No file read yet Country.all # File read happens here on first query ``` -------------------------------- ### Using Shortcuts with ActiveRecord Associations Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-associations.md Define associations with shortcuts to easily set and find records using attributes from the associated Active Hash model. This requires extending ActiveRecord models with `ActiveHash::Associations::ActiveRecordExtensions` and using `belongs_to_active_hash`. ```ruby class Country < ActiveHash::Base self.data = [ {:id => 1, :name => "US", :code => "US"}, {:id => 2, :name => "Canada", :code => "CA"} ] end class Person < ActiveRecord::Base extend ActiveHash::Associations::ActiveRecordExtensions belongs_to_active_hash :country, :shortcuts => [:name, :code] end # Create with shortcuts person = Person.new person.country_name = "US" person.country # => # # Before save, person.country_id is set to 1 person.save # Find via shortcut Person.find_by(country_code: "CA").country.name # => "Canada" ``` -------------------------------- ### Prevent ReservedFieldError in Ruby Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/types.md Avoid defining fields with names that are reserved by Active Hash to prevent ReservedFieldError. The 'attributes' field is an example of a reserved name. ```ruby class Country < ActiveHash::Base field :attributes # => raises ReservedFieldError end ``` -------------------------------- ### Create and Use a Condition Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/types.md Instantiate a Condition object with constraints and check if a record matches. ```ruby condition = Condition.new(name: 'US') condition.matches?(country_record) # => Boolean ``` -------------------------------- ### Create and Use Conditions Collection Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/types.md Instantiate a Conditions collection with an array of Condition objects and check if a record matches all of them. ```ruby conditions = Conditions.new([condition1, condition2]) conditions.matches?(record) # => Boolean if all match ``` -------------------------------- ### Get Computed Records Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-relation.md The `records` method returns an array of records that match the relation's conditions and order. It computes the results based on the applied filters. ```ruby relation = Country.all.where(language: 'English').order(name: :asc) records = relation.records # => [#, #] ``` -------------------------------- ### Get Full File Path Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-file-sources.md Constructs and returns the complete file path that ActiveHash will use to load data, based on the configured root path and filename. ```ruby class Country < ActiveFile::Base set_root_path "/app/data" set_filename "countries" end Country.full_path # => "/app/data/countries.yml" ``` -------------------------------- ### create! Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-base.md Create and save a new record. This method is intended to raise an error on failure, though ActiveHash always succeeds. ```APIDOC ## create! ### Description Create and save a new record, raise on failure. ### Method POST ### Endpoint /create! ### Parameters #### Request Body - **attributes** (Hash) - Optional - Initial attribute values ### Response #### Success Response (200) - **Record** (Object) - The newly created and saved record. ### Raises - Will not raise in ActiveHash (always succeeds), but signature matches ActiveRecord. ``` -------------------------------- ### Get single value or array of values from first record Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-relation.md Use `pick` to retrieve a single value or an array of values from specific columns of the first record in the relation. ```ruby Country.all.pick(:name) # => "US" (first record's name) ``` ```ruby Country.all.pick(:id, :name) # => [1, "US"] ``` -------------------------------- ### Set Multiple Filenames for Data Loading Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/api-reference-file-sources.md Specifies a list of filenames (without extensions) to be loaded when `use_multiple_files` is enabled. Each filename corresponds to a separate data file. ```ruby class Country < ActiveYaml::Base use_multiple_files set_filenames "europe", "americas", "asia", "africa" end ``` -------------------------------- ### ActiveYaml Usage with Aliases Source: https://github.com/active-hash/active_hash/blob/master/README.md After including ActiveYaml::Aliases and defining aliases in the YAML, you can access the aliased data directly from the model instances. This example shows accessing flavor and price. ```ruby class Soda < ActiveYaml::Base include ActiveYaml::Aliases end Soda.length # => 1 Soda.first.flavor # => sweet Soda.first.price # => 1.0 ``` -------------------------------- ### Access First, Last, and Specific Records Source: https://github.com/active-hash/active_hash/blob/master/_autodocs/quick-reference.md Get the first, last, or a specific record by its position (e.g., `.first`, `.last`, `.second`). Returns `nil` if the record doesn't exist. ```ruby Country.first, .last, .second # => Record or nil ```