Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does self.class.method work when including a module?

Tags:

ruby

I am using HTTParty, and based on the docs you can create a class :

class SomeClass 
    include HTTParty
    base_uri 'host'
    def index 
        self.class.get('/path')
    end
end

I am not sure how is get method declared inside the module.

like image 449
orestiss Avatar asked Jul 14 '26 22:07

orestiss


1 Answers

The get method is defined at line 484 of httparty/httparty.rb

def get(path, options = {}, &block)
  perform_request Net::HTTP::Get, path, options, &block
end

This is defined on a module called ClassMethods. If you look further up the file httparty/httparty.rb. At line 20 you will see:

def self.included(base)
  base.extend ClassMethods

The method included is called when a Module is included into another Module or Class.

This code ensures that when the HTTParty module is included into another module or class, the methods defined in HTTParty::ClassMethods are extended (added as class methods) onto the host object. They become class methods.

like image 89
11 revs, 10 users 40% Avatar answered Jul 19 '26 13:07

11 revs, 10 users 40%



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!