{
    "mode": "ri",
    "parameter": "ActiveRecord::Aggregations::ClassMethods",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/ri/ActiveRecord%3A%3AAggregations%3A%3AClassMethods/json",
    "generated": "2026-07-27T04:40:44Z",
    "sections": {
        "ActiveRecord::Aggregations::ClassMethods": {
            "content": "------------------------------------------------------------------------",
            "subsections": []
        },
        "Includes:": {
            "content": "Aggregations (from /home/chedong/.local/share/rdoc)\n\n(from /home/chedong/.local/share/rdoc)\n------------------------------------------------------------------------\nActive Record implements aggregation through a macro-like class method\ncalled #composedof for representing attributes as value objects. It\nexpresses relationships like \"Account [is] composed of Money [among\nother things]\" or \"Person [is] composed of [an] address\". Each call to\nthe macro adds a description of how the value objects are created from\nthe attributes of the entity object (when the entity is initialized\neither as a new object or from finding an existing object) and how it\ncan be turned back into attributes (when the entity is saved to the\ndatabase).\n\nclass Customer < ActiveRecord::Base\ncomposedof :balance, classname: \"Money\", mapping: %w(balance amount)\ncomposedof :address, mapping: [ %w(addressstreet street), %w(addresscity city) ]\nend\n\nThe customer class now has the following methods to manipulate the value\nobjects:\n* Customer#balance, Customer#balance=(money)\n* Customer#address, Customer#address=(address)\n\nThese methods will operate with value objects like the ones described\nbelow:\n\nclass Money\ninclude Comparable\nattrreader :amount, :currency\nEXCHANGERATES = { \"USDTODKK\" => 6 }\n\ndef initialize(amount, currency = \"USD\")\n@amount, @currency = amount, currency\nend\n\ndef exchangeto(othercurrency)\nexchangedamount = (amount * EXCHANGERATES[\"#{currency}TO#{othercurrency}\"]).floor\nMoney.new(exchangedamount, othercurrency)\nend\n\ndef ==(othermoney)\namount == othermoney.amount && currency == othermoney.currency\nend\n\ndef <=>(othermoney)\nif currency == othermoney.currency\namount <=> othermoney.amount\nelse\namount <=> othermoney.exchangeto(currency).amount\nend\nend\nend\n\nclass Address\nattrreader :street, :city\ndef initialize(street, city)\n@street, @city = street, city\nend\n\ndef closeto?(otheraddress)\ncity == otheraddress.city\nend\n\ndef ==(otheraddress)\ncity == otheraddress.city && street == otheraddress.street\nend\nend\n\nNow it's possible to access attributes from the database through the\nvalue objects instead. If you choose to name the composition the same as\nthe attribute's name, it will be the only way to access that attribute.\nThat's the case with our balance attribute. You interact with the value\nobjects just like you would with any other attribute:\n\ncustomer.balance = Money.new(20)     # sets the Money value object and the attribute\ncustomer.balance                     # => Money value object\ncustomer.balance.exchangeto(\"DKK\")  # => Money.new(120, \"DKK\")\ncustomer.balance > Money.new(10)     # => true\ncustomer.balance == Money.new(20)    # => true\ncustomer.balance < Money.new(5)      # => false\n\nValue objects can also be composed of multiple attributes, such as the\ncase of Address. The order of the mappings will determine the order of\nthe parameters.\n\ncustomer.addressstreet = \"Hyancintvej\"\ncustomer.addresscity   = \"Copenhagen\"\ncustomer.address        # => Address.new(\"Hyancintvej\", \"Copenhagen\")\n\ncustomer.address = Address.new(\"May Street\", \"Chicago\")\ncustomer.addressstreet # => \"May Street\"\ncustomer.addresscity   # => \"Chicago\"\n",
            "subsections": [
                {
                    "name": "Writing value objects",
                    "content": "Value objects are immutable and interchangeable objects that represent a\ngiven value, such as a Money object representing $5. Two Money objects\nboth representing $5 should be equal (through methods such as == and <=>\nfrom Comparable if ranking makes sense). This is unlike entity objects\nwhere equality is determined by identity. An entity class such as\nCustomer can easily have two different objects that both have an address\non Hyancintvej. Entity identity is determined by object or relational\nunique identifiers (such as primary keys). Normal ActiveRecord::Base\nclasses are entity objects.\n\nIt's also important to treat the value objects as immutable. Don't allow\nthe Money object to have its amount changed after creation. Create a new\nMoney object with the new value instead. The Money#exchangeto method is\nan example of this. It returns a new value object instead of changing\nits own values. Active Record won't persist value objects that have been\nchanged through means other than the writer method.\n\nThe immutable requirement is enforced by Active Record by freezing any\nobject assigned as a value object. Attempting to change it afterwards\nwill result in a RuntimeError.\n\nRead more about value objects on http://c2.com/cgi/wiki?ValueObject and\non the dangers of not keeping value objects immutable on\nhttp://c2.com/cgi/wiki?ValueObjectsShouldBeImmutable\n"
                },
                {
                    "name": "Custom constructors and converters",
                    "content": "By default value objects are initialized by calling the new constructor\nof the value class passing each of the mapped attributes, in the order\nspecified by the :mapping option, as arguments. If the value class\ndoesn't support this convention then #composedof allows a custom\nconstructor to be specified.\n\nWhen a new value is assigned to the value object, the default assumption\nis that the new value is an instance of the value class. Specifying a\ncustom converter allows the new value to be automatically converted to\nan instance of value class if necessary.\n\nFor example, the NetworkResource model has networkaddress and\ncidrrange attributes that should be aggregated using the NetAddr::CIDR\nvalue class (https://www.rubydoc.info/gems/netaddr/1.5.0/NetAddr/CIDR).\nThe constructor for the value class is called create and it expects a\nCIDR address string as a parameter. New values can be assigned to the\nvalue object using either another NetAddr::CIDR object, a string or an\narray. The :constructor and :converter options can be used to meet these\nrequirements:\n\nclass NetworkResource < ActiveRecord::Base\ncomposedof :cidr,\nclassname: 'NetAddr::CIDR',\nmapping: [ %w(networkaddress network), %w(cidrrange bits) ],\nallownil: true,\nconstructor: Proc.new { |networkaddress, cidrrange| NetAddr::CIDR.create(\"#{networkaddress}/#{cidrrange}\") },\nconverter: Proc.new { |value| NetAddr::CIDR.create(value.isa?(Array) ? value.join('/') : value) }\nend\n\n# This calls the :constructor\nnetworkresource = NetworkResource.new(networkaddress: '192.168.0.1', cidrrange: 24)\n\n# These assignments will both use the :converter\nnetworkresource.cidr = [ '192.168.2.1', 8 ]\nnetworkresource.cidr = '192.168.0.1/24'\n\n# This assignment won't use the :converter as the value is already an instance of the value class\nnetworkresource.cidr = NetAddr::CIDR.create('192.168.2.1/8')\n\n# Saving and then reloading will use the :constructor on reload\nnetworkresource.save\nnetworkresource.reload\n"
                },
                {
                    "name": "Finding records by a value object",
                    "content": "Once a #composedof relationship is specified for a model, records can\nbe loaded from the database by specifying an instance of the value\nobject in the conditions hash. The following example finds all customers\nwith addressstreet equal to \"May Street\" and addresscity equal to\n\"Chicago\":\n\nCustomer.where(address: Address.new(\"May Street\", \"Chicago\"))\n------------------------------------------------------------------------"
                }
            ]
        },
        "Instance methods:": {
            "content": "composedof\n",
            "subsections": []
        }
    },
    "flags": [],
    "examples": [],
    "see_also": []
}