Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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.

like image 283
Misha Moroshko Avatar asked Jan 15 '11 11:01

Misha Moroshko


People also ask

How do you define a class method in Ruby?

There are two standard approaches for defining class method in Ruby. The first one is the “def self. method” (let's call it Style #1), and the second one is the “class << self” (let's call it Style #2). Both of them have pros and cons.

CAN modules have private methods Ruby?

You can only use private methods with:Other methods from the same class. Methods inherited from the parent class. Methods included from a module.

Can we define module inside class Ruby?

Discussion. You can define and access instance variables within a module's instance methods, but you can't actually instantiate a module. A module's instance variables exist only within objects of a class that includes the module.

CAN modules have instance variables Ruby?

Explanation: Yes, Module instance variables are present in the class when you would include them inside the class.


2 Answers

Yep

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

One possible note I should add - if the module is going to be ALL class methods - better off just using extend ModuleName in the Model and defining the methods directly in the module instead - rather than having a ClassMethods module inside the Module, a la

 module ModuleName    def foo      # stuff    end  end 
like image 148
Omar Qureshi Avatar answered Sep 18 '22 15:09

Omar Qureshi


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 
like image 31
Mladen Jablanović Avatar answered Sep 19 '22 15:09

Mladen Jablanović