gpt4 book ai didi

ruby-on-rails - Ruby 扩展并包含跟踪代码

转载 作者:太空宇宙 更新时间:2023-11-03 17:20:17 24 4
gpt4 key购买 nike

我对使用“include”和“extend”感到困惑,在搜索了几个小时之后,我得到的只是与类实例一起使用的模块方法,包括模块,以及当类扩展这些方法的模块。

但这并没有帮助我弄清楚为什么这段代码在注释“#extend Inventoryable”中的扩展模块行时出错在取消注释时工作,这是代码

module Inventoryable

def create(attributes)
object = new(attributes)
instances.push(object)
return object
end

def instances
@instances ||= []
end

def stock_count
@stock_count ||= 0
end

def stock_count=(number)
@stock_count = number
end

def in_stock?
stock_count > 0
end
end

class Shirt
#extend Inventoryable
include Inventoryable
attr_accessor :attributes

def initialize(attributes)
@attributes = attributes
end
end

shirt1 = Shirt.create(name: "MTF", size: "L")
shirt2 = Shirt.create(name: "MTF", size: "M")
puts Shirt.instances.inspect

输出是

store2.rb:52:in `<main>': undefined method `create' for Shirt:Class (NoMethodError)

当取消注释“extend Inventoryable”以使代码工作时:

module Inventoryable

def create(attributes)
object = new(attributes)
instances.push(object)
return object
end

def instances
@instances ||= []
end

def stock_count
@stock_count ||= 0
end

def stock_count=(number)
@stock_count = number
end

def in_stock?
stock_count > 0
end
end

class Shirt
extend Inventoryable
include Inventoryable
attr_accessor :attributes

def initialize(attributes)
@attributes = attributes
end
end

shirt1 = Shirt.create(name: "MTF", size: "L")
shirt2 = Shirt.create(name: "MTF", size: "M")
puts Shirt.instances.inspect

使代码运行并输出以下内容

[#<Shirt:0x0055792cb93890 @attributes={:name=>"MTF", :size=>"L"}>, #<Shirt:0x0055792cb937a0 @attributes={:name=>"MTF", :size=>"M"}>] 

这有点令人困惑,但我只需要知道,为什么我需要扩展模块以避免错误?,以及如何编辑此代码以使其在没有扩展方法的情况下工作? ,代码中还剩下什么仍然依赖于扩展?

最佳答案

当您扩展 一个模块时,该模块中的方法变成“类方法”**。因此,当您扩展 Inventoryable 时,create 将作为 Shirt 类的一个方法可用。

当您包含 一个模块时,该模块中的方法变成“实例方法”**。因此,当您包含 Inventoryable 时,createShirt 类上不可用(但在实例上可用衬衫)。

要在使用 include 时使 createShirt 类上可用,您可以使用 included Hook 。这可能看起来像:

module Inventoryable
module ClassMethods

def create
puts "create!"
end

end

module InstanceMethods

end

def self.included(receiver)
receiver.extend ClassMethods
receiver.include InstanceMethods
end
end

那么如果你这样做:

class Shirt
include Invetoryable
end

你可以这样做:

> Shirt.create
create!
=> nil

** 人群中的 ruby​​ 纯粹主义者会正确地指出,在 ruby​​ 中,一切都是实例方法,没有类方法。这在形式上是 100% 正确的,但我们将在此处使用 classinstance 方法的通俗含义。

关于ruby-on-rails - Ruby 扩展并包含跟踪代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49932510/

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