【译】提取到组件类中(Extract to composed class)

Sunday, July 25, 2010

原文:http://rails-bestpractices.com/posts/18-extract-to-composed-class
如果一个模型中有一些关联字段, 比如一个用户有一个address_city和一个address_street, 你可以把它们提取到组件类中去
ps: 是翻译成组件类么?:-)

丑陋的...

# == Schema Information
#  address_city        :string(255)
#  address_street      :string(255)
class Customer < ActiveRecord::Base
  def address_close_to?(other_customer)
    address_city == other_cutomer.address_city
  end

def address_equal(other_customer)
    address_street == other_customer.address_street &&
      address_city == other_customer.address_city
  end
end

可以看到Customer有两个属性address_city 和 address_street, 但是应该是Address的属性,
如果你不想创建一个addresses的数据库表的话,你只要创建一个组件类Address。

重构...

class Customer < ActiveRecord::Base
  composed_of :address, :mapping => [ %w(address_street street), %w(address_city city)]
end

class Address
  attr_reader :street, :city

def initialize(street, city)
    @street, @city = street, city
  end

def close_to?(other_address)
    city == other_address.city
  end

def ==(other_address)
    city == other_address.city && street == other_address.street
  end
end

Rails提供了一个帮助方法composed_of
来方便的提取一个组件类,这里我们为Customer添加了一个叫Address的组件类,在Address模型中我们使用了street
和city属性,并且和Customer模型中的address_street和address_city对应

This entry was tagged Rails and Best-Practices

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top