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