代码之家  ›  专栏  ›  技术社区  ›  fig

由钢轨组成-何时使用?

  •  18
  • fig  · 技术社区  · 16 年前

    什么时候应该使用activerecord的 composed_of 上课方法?

    2 回复  |  直到 14 年前
        1
  •  22
  •   Staelen    16 年前

    就我个人而言,我认为当你拥有数据库中没有存储的对象时,如数据库中所示,这是有用的,例如温度、GPS位置、天平等。

    你可能会问,为什么这些数据没有存储在数据库中?在数据库中,我们只存储一个值,但是如果我们想为该值附加有用的相关方法,

    例如

    1. 在温度方面,我们可能需要像 to_fahrenheit , to_celsius , is_boiling_point? 等

    2. 在GPS定位的情况下,我们可能需要像 distance_from(point) , route_to(point) 等

    因此,当我们可以为这些对象创建类,并使用composed_of动态初始化这些对象时,它非常有用

    希望有帮助=)

        2
  •  3
  •   Florin    14 年前

    一个更复杂的例子 composed_of 具有 Money :

    composed_of :price,
      :class_name => "Money",
      :mapping => [%w(cents cents), %w(currency currency_as_string)],
      :constructor => Proc.new { |cents, currency| Money.new(cents || 0, currency || Money.default_currency) },
      :converter => Proc.new { |value| value.respond_to?(:to_money) ? value.to_money : raise(ArgumentError, "Can't convert #{value.class} to Money") }
    

    来源: github wiki .

    推荐文章