Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #4719 (new enhancement)

Opened 3 years ago

[PATCH] composed_of :by_prefix option

Reported by: anonymous Assigned to: David
Priority: normal Milestone:
Component: ActiveRecord Version:
Severity: normal Keywords: composed_of
Cc: the.liberal.media@gmail.com

Description

After reading ticket #3830 regarding changing default mapping behavior of composed_of, I decided to do a bit of digging to see if the proposed enhancement was possible. From what I could tell, inferring the the column names from the target class would be unpredictable and possibly inconsistent.

Instead, I decided to experiment with a :by_prefix option to composed_of that would eliminate the need for explicit mapping. The mapped columns are inferred by a prefixd convention.

Attached is a patch resulting from my work. It works well, but introduces a bit more processing at "runtime" (after evals, etc.). I am very new to both Ruby and Rails, so there may be some inefficiencies in the implementation but, for the most part, it should be fairly "tight" code. All unit tests were successful.

Sample Usage

Data Definition

CREATE TABLE customers (
  id int,
  name varchar,
  address_city varchar,
  address_state varchar,
  address_country varchar,
  primary key (id)
);

Model

class Customer < ActiveRecord::Base
  composed_of :address, :by_prefix
end

The :by_prefix option works both as a second param value and as a Hash key, so it can accept an alternate prefix.

class Customer < ActiveRecord::Base
  composed_of :address, :by_prefix => "addr_"
end

Aggregate Class

Notice the difference in the way the constructor accepts parameters.

class Address
  attr_reader :city, :state, :country
  def initialize(bits)
    @city, @state, @country = bits[:city], bits[:state], bits[:country]
  end
end

Criticism is always welcome.

dz

Attachments

composed_of_by_prefix.diff (10.6 kB) - added by anonymous on 04/13/06 02:39:06.
composed_of :by_prefix

Change History

04/13/06 02:39:06 changed by anonymous

  • attachment composed_of_by_prefix.diff added.

composed_of :by_prefix