ruby - Why the module `ClassMethods` defined and extended in the same namespace? -


i trying understand code github repo. it's main module of gem setup client.

module github   # more code   class << self     def included(base)       base.extend classmethods # for?     end     def new(options = {}, &block)       client.new(options, &block)     end     def method_missing(method_name, *args, &block)       if new.respond_to?(method_name)         new.send(method_name, *args, &block)       elsif configuration.respond_to?(method_name)         github.configuration.send(method_name, *args, &block)       else         super       end     end     def respond_to?(method_name, include_private = false)       new.respond_to?(method_name, include_private) ||       configuration.respond_to?(method_name) ||       super(method_name, include_private)     end   end    module classmethods     def require_all(prefix, *libs)       libs.each |lib|         require "#{file.join(prefix, lib)}"       end     end     # more methods ...   end    extend classmethods   require_all libdir,     'authorization',     'validations',     'normalizer',     'parameter_filter',     'api',     'client',     'pagination',     'request',     'response',     'response_wrapper',     'error',     'mime_type',     'page_links',     'paged_request',     'page_iterator',     'params_hash'  end 
  1. why class << self , module classmethods used, , extended instead of being included in class << self part?
  2. there class method def included(base). seems add class methods specific object. why this? relate functionality of class, not understand it.

module mymodule   class << self     def included(base)       base.extend classmethods # for?     end     <...>   end   <...> end 

this pretty common practice in ruby. basically, it's saying is: when object performs include mymodule, make extend mymodule::classmethods. such feat useful if want mixin adds methods not instances of class, class itself.

a short example:

module m   # normal instance method   def mul     @x * @y   end    module classmethods     # class method     def factory(x)       new(x, 2 * x)     end   end    def self.included(base)     base.extend classmethods   end end  class p   include m   def initialize(x, y)     @x = x     @y = y   end    def sum     @x + @y   end end  p1 = p.new(5, 15) puts "#{p1.sum} #{p1.mul}"  # calling class method module here! p2 = p.factory(10) puts "#{p2.sum} #{p2.mul}" 

Comments

Popular posts from this blog

javascript - oscilloscope of speaker input stops rendering after a few seconds -

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -