首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ruby要求循环

Ruby要求循环
EN

Stack Overflow用户
提问于 2014-05-26 21:08:32
回答 1查看 517关注 0票数 1

我有以下代码(简化):

decorator.rb

代码语言:javascript
复制
require 'decoratable'

class Decorator < SimpleDelegator
  include Decoratable
end

decoratable.rb

代码语言:javascript
复制
require 'decorator_builder'

module Decoratable
  def decorate(*decorators)
    decorators.inject(DecoratorBuilder.new(self)) do |builder, decorator|
      builder.public_send(decorator)
    end.build
  end
end

decorator_builder.rb

代码语言:javascript
复制
require 'rare_decorator'

class DecoratorBuilder

  def initialize(card)
    @card = card
    @decorators = []
  end

  def rare
    @decorators << ->(card) { RareDecorator.new(card) }
    self
  end

  def build
    @decorators.inject(@card) do |card, decorator|
      decorator.call(card)
    end
  end

end

rare_decorator.rb

代码语言:javascript
复制
require 'decorator'

class RareDecorator < Decorator
  # Stuff here
end

当我需要decorator.rb时,它会导致在声明RareDecorator之前声明RareDecorator,这是一个问题,因为RareDecorator是从Decorator继承的。

一个可能的解决方案是像这样拆分decorator.rb:

代码语言:javascript
复制
class Decorator < SimpleDelegator; end

require 'decoratable'

class Decorator
  include Decoratable
end

然而,对我来说,在文件中间声明依赖关系似乎并不是一个非常干净的解决方案。

这个问题有更好的解决办法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-26 22:06:09

不要在每个文件中指定需求,而是创建一个需要所有应用程序需求的文件。例如,将其称为environment.rb

代码语言:javascript
复制
require 'decoratable'
require 'decorator'
require 'decorator_builder'
require 'rare_decorator'

您不需要担心Decoratable不知道什么是DecoratorBuilder,因为它在方法中使用,调用该方法时将执行对常量的检查。因为你需要装饰片刻后,一切都会工作。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23877750

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档