【问题标题】:ruby class instance variable configuration patternruby 类实例变量配置模式
【发布时间】:2016-09-28 19:56:35
【问题描述】:

我正在尝试为包含模块的类进行类似 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

【问题讨论】:

  • 我还没有完全理解这个问题。你期待f = Foo.new; f.dog_breed = :chimp; puts Foo.dog_breed 的输出是什么?类中的哪些常量对您有帮助?

标签: ruby configuration


【解决方案1】:

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

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 以从模块中获取实例和类常量查找,但它确实有效。我不确定我是否真的喜欢这个解决方案。好问题,尽管您可以添加一些细节。

【讨论】:

  • 是的,这个例子有点随机,更多的是为了配置,这个例子让它看起来可以通过继承来处理(breed
猜你喜欢
  • 2014-09-21
  • 2013-03-24
  • 2021-07-29
  • 1970-01-01
  • 1970-01-01
  • 2013-11-26
  • 2015-08-13
  • 1970-01-01
  • 2010-10-24
相关资源
最近更新 更多