Ruby: Is it possible to define a class method in a module?

ruby

Solution

module Common
  def foo
    puts 'foo'
  end
end

class A
  extend Common
end

class B
  extend Common
end

class C
  extend Common
end

A.foo

Or, you can extend the classes afterwards:

class A
end

class B
end

class C
end

[A, B, C].each do |klass|
  klass.extend Common
end

Problem

Say there are three classes: `A`, `B` & `C`. I want each class to have a class method, say `self.foo`, that has exactly the same code for `A`, `B` & `C`. Is it possible to define `self.foo` in a module and include this module in `A`, `B` & `C`? I tried to do so and got an error message saying that `foo` is not recognized.

Original source