gpt4 book ai didi

ruby-on-rails - 从gem继承一个类并添加本地方法

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

我使用 gem 来管理 gmail api 集成的某些属性,我对它的工作方式非常满意。

我想添加一些本地方法来作用于该 gem 中使用的 Gmail::Message 类。

即我想做这样的事情。

models/GmailMessage.rb
class GmailMessage < Gmail::Message

def initialize(gmail)
#create a Gmail::Message instance as a GmailMessage instance
self = gmail
end

def something_clever
#do something clever utilising the Gmail::Message methods
end
end

我不想坚持下去。但显然我不能那样定义 self 。

为了澄清,我想获取 Gmail::Message 的实例并创建一个 GmailMessage 实例,它是另一封邮件的直接副本。

然后我可以运行 @gmail.subject 和 @gmail.html 之类的方法,但也可以运行 @gmail.something_clever... 并在必要时保存本地属性。

我是不是疯了?

最佳答案

您可以使用 mixin 的概念,其中您在另一个类中包含一个 Module 以使用附加功能增强它。

这是如何做到的。为了创建一个完整的工作示例,我创建了类似于您的代码库中可能拥有的模块。

# Assumed to be present in 3rd party gem, dummy implementation used for demonstration
module Gmail
class Message
def initialize
@some_var = "there"
end
def subject
"Hi"
end
end
end

# Your code
module GmailMessage
# You can code this method assuming as if it is an instance method
# of Gmail::Message. Once we include this module in that class, it
# will be able to call instance methods and access instance variables.
def something_clever
puts "Subject is #{subject} and @some_var = #{@some_var}"
end
end

# Enhance 3rd party class with your code by including your module
Gmail::Message.include(GmailMessage)

# Below gmail object will actually be obtained by reading the user inbox
# Lets create it explicitly for demonstration purposes.
gmail = Gmail::Message.new

# Method can access methods and instance variables of gmail object
p gmail.something_clever
#=> Subject is Hi and @some_var = there

# You can call the methods of original class as well on same object
p gmail.subject
#=> "Hi"

关于ruby-on-rails - 从gem继承一个类并添加本地方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34767399/

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