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

Say there are three classes: A , B and C I want each class to have a class method, for example self.foo , which has exactly the same code for A , B and C

Is it possible to define self.foo in a module and enable this module in A , B and C ? I tried to do this and received an error message stating that foo not recognized.

+56
ruby
Jan 15 '11 at 11:37
source share
5 answers
 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 after this:

 class A end class B end class C end [A, B, C].each do |klass| klass.extend Common end 
+44
Jan 15 2018-11-15T00:
source share

Yes

 module Foo def self.included(base) base.extend(ClassMethods) end module ClassMethods def some_method # stuff end end end 

One of the possible comments that I should add: if the module will be used by all methods of the class, it is better to use only extend ModuleName in the model and define methods directly in the module instead, instead of having the ClassMethods module inside the module, a la

  module ModuleName def foo # stuff end end 
+98
Jan 15 '11 at 11:41
source share

Rails 3 introduced a module called ActiveSupport::Concern , which aims to simplify the syntax of modules.

 module Foo extend ActiveSupport::Concern module ClassMethods def some_method # stuff end end end 

This allowed us to save several lines of code for the “template” in the module.

+21
Jun 26 '15 at 12:51 on
source share

This is the basic ruby ​​mixin functionality that makes ruby ​​so special. While extend turns module methods into class methods, include turns module methods into instance methods in the inclusion / extension class / module.

 module SomeClassMethods def a_class_method 'I´ma class method' end end module SomeInstanceMethods def an_instance_method 'I´m an instance method!' end end class SomeClass include SomeInstanceMethods extend SomeClassMethods end instance = SomeClass.new instance.an_instance_method => 'I´m an instance method!' SomeClass.a_class_method => 'I´ma class method' 
+18
Dec 09 '16 at 10:27
source share

Just wanted to expand Oliver's answer Define class methods and instance methods together in a module.

 module Foo def self.included(base) base.extend(ClassMethods) end module ClassMethods def a_class_method puts "ClassMethod Inside Module" end end def not_a_class_method puts "Instance method of foo module" end end class FooBar include Foo end FooBar.a_class_method FooBar.methods.include?(:a_class_method) FooBar.methods.include?(:not_a_class_method) fb = FooBar.new fb.not_a_class_method fb.methods.include?(:not_a_class_method) fb.methods.include?(:a_class_method) 
0
Jun 28 '19 at 3:36
source share



All Articles