Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add class methods and instance methods from the same module?

Tags:

ruby

Newbie question:

I know how include and extend work, what I am wondering is if there is a way to get both class and instance methods from a single module?

This is how I do it with two modules:

module InstanceMethods
    def mod1
        "mod1"
    end
end

module ClassMethods
    def mod2
        "mod2"
    end
end

class Testing
    include InstanceMethods
    extend ClassMethods 
end

t = Testing.new
puts t.mod1
puts Testing::mod2

Thanks for taking your time ...

like image 757
Roger Nordqvist Avatar asked May 13 '13 15:05

Roger Nordqvist


People also ask

Can a class method be called on an instance?

A class method is a method that's shared among all objects. To call a class method, put the class as the first argument. Class methods can be can be called from instances and from the class itself.

Are modules and methods same?

"method" is a function that is a attached to an object or class. A module is a group of defined functions, classes, consrants, etc.

How do you call a method in a module?

The method definitions look similar, too: Module methods are defined just like class methods. As with class methods, you call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons.


2 Answers

Yes. It's exactly as simple as you would expect, due to the genius of ruby:

module Methods
    def mod
        "mod"
    end
end

class Testing
    include Methods # will add mod as an instance method
    extend Methods # will add mod as a class method
end

t = Testing.new
puts t.mod
puts Testing::mod

Or, you could do:

module Methods
    def mod1
        "mod1"
    end

    def mod2
        "mod2"
    end
end

class Testing
    include Methods # will add both mod1 and mod2 as instance methods
    extend Methods # will add both mod1 and mod2 as class methods
end

t = Testing.new
puts t.mod1
puts Testing::mod2
# But then you'd also get
puts t.mod2
puts Testing::mod1
like image 137
Magne Avatar answered Oct 29 '22 01:10

Magne


module Foo
 def self.included(m)
   def m.show1
     p "hi"
   end
 end

 def show2
   p "hello"

 end
end

class Bar
 include Foo
end

Bar.new.show2 #=> "hello"
Bar.show1 #=> "hi"
like image 33
Arup Rakshit Avatar answered Oct 29 '22 01:10

Arup Rakshit