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.
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.
You can only use private methods with:Other methods from the same class. Methods inherited from the parent class. Methods included from a module.
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.
Explanation: Yes, Module instance variables are present in the class when you would include them inside the class.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With