gpt4 book ai didi

ruby - 为什么模块 `ClassMethods` 在同一个命名空间中定义和扩展?

转载 作者:数据小太阳 更新时间:2023-10-29 06:33:28 26 4
gpt4 key购买 nike

我正在尝试理解来自 github repo 的代码.它是设置客户端的 gem 的主要模块。

module Github
# more code
class << self
def included(base)
base.extend ClassMethods # what would this be 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 do |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. 为什么是class << selfmodule ClassMethods使用,然后扩展而不是包含在 class << self 中部分?
  2. 有一个类方法def included(base) .这似乎将类方法添加到特定对象中。为什么会这样?它可能与类的功能有关,但我不明白。

最佳答案

module MyModule
class << self
def included(base)
base.extend ClassMethods # what would this be for?
end
<...>
end
<...>
end

这实际上是 Ruby 中很常见的做法。基本上,它的意思是:当某个对象执行 include MyModule 时,也使它也 extend MyModule::ClassMethods。如果您想要一个 mixin 不仅向类的实例添加一些方法,而且向类本身添加一些方法,这样的壮举很有用。

一个简短的例子:

module M
# A normal instance method
def mul
@x * @y
end

module ClassMethods
# A 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}" # <= 20 75

# Calling the class method from the module here!
p2 = P.factory(10)
puts "#{p2.sum} #{p2.mul}" # <= 30 200

关于ruby - 为什么模块 `ClassMethods` 在同一个命名空间中定义和扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30757126/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com