Andrey Moroz Andrey Moroz - 6 months ago 12
Ruby Question

Rails concern how to call ClassMethods from InstanceMethod

I need to call

weight_to_kg
class method from instance method.

I would like to create weight to kg converter for a lot of my models, that have weight column in pounds.

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


How can I do it?

Answer

self.class.weight_to_kg(weight)