Rails关注如何从InstanceMethod调用ClassMethods

And*_*roz 1 ruby ruby-on-rails activesupport-concern

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

我想为我的很多模型创建重量到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
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

e-f*_*her 7

self.class.weight_to_kg(weight)