1

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.

0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.