Rails关注InstanceMethod如何调用ClassMethods

Rails concern how to call ClassMethods from InstanceMethod

我需要从实例方法.

调用weight_to_kgclass方法

我想为我的很多模型创建重量到千克的转换器,它们的重量列以磅为单位。

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

我该怎么做?

self.class.weight_to_kg(weight)

我觉得这个可以更简单的表达;我认为您不需要超过 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.