Rails关注如何从InstanceMethod调用ClassMethods

时间:2016-05-10 12:13:31

标签: ruby-on-rails ruby 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

我该怎么做?

2 个答案:

答案 0 :(得分:6)

self.class.weight_to_kg(weight)

答案 1 :(得分: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.