Bhimasen Rautaray
Bhimasen Rautaray

Reputation: 301

how to call same module method as instance method and class method in ruby class

I want to call the same module method as a class method as well as an instance method in Ruby class. example

module Mod1
  def method1
  end
end

class A
end

I want to call method1 like A.new.method1 or A.method1.

Upvotes: 1

Views: 84

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

As @Karthik mentioned, you can have the class include and extend the module:

module Mod1
  def method1
    'hi'    
  end
end

class A
end

A.include Mod1
A.extend Mod1

A.new.method1 #=> 'hi'
A.method1     #=> 'hi'

A.extend Mod1 is nothing more than

A.singleton_class.include Mod1

When this is to be done it is not unusual to see the module written as follows.

module Mod1
  def method1
    'hi'
  end      
  def self.included(klass)
    klass.extend(self)
  end
end

In this case the module need only be included by the class:

class A
end

A.include Mod1

A.new.method1 #=> 'hi'
A.method1     #=> 'hi'

Module::included is referred to as a callback or hook method. A.include Mod1 causes Mod1::included to be executed with klass equal to A and self equal to Mod1.

As an aside, there are several other callback methods that can be used to good effect. Arguably, the most important are Module::extended, Module::prepended and Class::inherited.

Upvotes: 2

Karthik T
Karthik T

Reputation: 31952

I cant imagine this is a good design.. but you can try to both include and extend the module into the class. include adds the methods as instance methods and `e http://www.railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/

Upvotes: 1

Related Questions