1

我需要从实例方法调用weight_to_kg 方法。

我想为我的许多模型创建重量到公斤的转换器,这些模型的重量列以磅为单位。

module WeightConvertor
  extend ActiveSupport::Concern

  def weight_kg
    # I need to call weight_to_kg method
    ClassMethods.weight_to_kg(weight) # does not work
  end

  module ClassMethods
    def weight_to_kg(weight)
    end
  end
end

class Order < ActiveRecord::Base
  include WeightConvertor
  # weight column is present
end

Order.first.weight
Order.first.weight_kg

我该怎么做?

4

2 回答 2

7

self.class.weight_to_kg(weight)

于 2016-05-10T12:28:48.347 回答
0

我认为这可以更简单地表达;我认为您不需要超过 1 个模块:

#!/usr/bin/env ruby

module WeightConverter

    LB_PER_KG = 2.20462262

    def weight_kg
        weight / LB_PER_KG
    end
end


class Order
    include WeightConverter
    attr_accessor :weight

    def initialize(weight)
        @weight = weight
    end
end

order = Order.new(22.0462262)
puts "Order weighs #{order.weight} lbs, which is #{order.weight_kg} kg."

# Output: Order weighs 22.0462262 lbs, which is 10.0 kg.
于 2016-05-10T12:58:01.933 回答