gpt4 book ai didi

ruby 类实例变量配置模式

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

我正在尝试为包含模块的类创建类似 DSL 的配置,但要使配置的变量对类和实例方法都可用,似乎需要在模块中使用访问方法。有没有更优雅的方法来做到这一点?

module DogMixin  
class << self
def included(base)
base.extend ClassMethods
end
end

module ClassMethods
def breed(value)
@dog_breed = value
end

def dog_breed
@dog_breed
end
end
end

class Foo
include DogMixin

breed :havanese
end

puts Foo.dog_breed
# not implemented but should be able to do this as well
f = Foo.new
f.dog_breed

最佳答案

我觉得你的例子有点奇怪:)无论如何,避免编写访问器(赋值 - 访问器在我看来是有问题的 - 特别是在给定的示例中)的一种方法是定义常量,如下例所示。但是,如果您需要运行时分配,请编辑您的问题(并因此使此答案无效 :) 除非您想弄乱运行时常量分配,这是可能的但很麻烦)。

module DogMixin
# **include** DogMixin to get `Class.dog_breed`
class << self
def included(base)
def base.dog_breed
self::DOG_BREED || "pug"
end
end
end

# **extend** DogMixin to get `instance.dog_breed`
def dog_breed
self.class.const_get(:DOG_BREED) || "pug"
end
end

class Foomer
DOG_BREED = 'foomer'
extend DogMixin
include DogMixin
end

f = Foomer.new
puts Foomer.dog_breed
puts f.dog_breed

# If I understand you correctly, this is the most important (?):
f.dog_breed == Foomer.dog_breed #=> true

阅读了一些(In Ruby) allowing mixed-in class methods access to class constants从模块中获取实例和类常量查找,但它有效。我不确定我是否真的喜欢这个解决方案。好问题,尽管您可以添加一些细节。

关于ruby 类实例变量配置模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39756573/

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