gpt4 book ai didi

ruby - 在 define_method 定义的方法上调用 super

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

我创建了一个 Model 类,我在其中定义了基于 User(继承自 Model)中调用的方法(属性)的方法。问题是我不能覆盖define_method定义的方法,并调用super传递给定义的方法。我猜这是因为定义的方法被添加到用户本身,而不是模型,所以它实际上在父类(super class)(即模型)中没有方法。

之所以要这样做,是因为大多数属性应该直接保存到数据库中,而一些属性,如密码,需要一些额外的处理。

class Model
def self.attribute(name)
define_method(name) do
self
end
end
end

class User < Model
attribute :password
end

class User2 < Model
attribute :password

def password
super
end
end

@user = User.new
puts @user.password # => <User:0x00000100845540>

@user2 = User2.new
puts @user2.password
# define_super.rb:17:in `password': super: no superclass method
# `password' for #<User2:0x00000100845578> (NoMethodError)
# from define_super.rb:25:in `<main>'

有什么方法可以更改代码以使其正常工作吗?我需要一种方法来覆盖动态创建的方法。

最佳答案

父类(super class)上定义方法:

class Model
def self.attribute(name)
superclass.send :define_method, name do
self
end
end
end

关于ruby - 在 define_method 定义的方法上调用 super,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1994978/

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