我有以下代码(简化):
decorator.rb
require 'decoratable'
class Decorator < SimpleDelegator
include Decoratable
end
decoratable.rb
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
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
require 'decorator'
class RareDecorator < Decorator
# Stuff here
end
当我需要decorator.rb时,它会导致在声明Decorator之前声明RareDecorator,这是一个问题,因为RareDecorator继承了Decorator。
一种可能的解决方案是将decorator.rb拆分为:
class Decorator < SimpleDelegator; end
require 'decoratable'
class Decorator
include Decoratable
end
但是,在文件中间声明依赖关系似乎对我来说似乎不是一个非常干净的解决方案。
这个问题有更好的解决方案吗?
答案 0 :(得分:3)
不是在每个文件中指定要求,而是创建一个需要所有应用程序要求的文件。将其称为例如environment.rb
:
require 'decoratable'
require 'decorator'
require 'decorator_builder'
require 'rare_decorator'
您不必担心Decoratable
不知道DecoratorBuilder
是什么,因为它在方法中使用,并且在调用此方法时将执行对常量的检查。由于你以后需要装饰师,所以一切都会有效。