Вопрос

I've started working with decorators at my new job and am finding them really helpful. I'm working on writing specs for one of our decorators and wondered if it was possible to do this...

Setup (the stripped down version):

We have a main object with two children.

 Main
 / \
A   B

When Main gets decorated we also decorate B, but we must pass A through as context. A is used for a few of B's decorator methods but it makes more logical sense to separate A from B as above.

# in MainDecorator    
BDecorator.new(B, context: {a: A}) # all good

Occasionally we decorate B on it's own (without going through Main) and we've forgotten to pass A through as context in the past. We always catch it, but it's an annoying issue to keep hitting.

B.decorate # no context -> :(

Question:

Is it possible to validate that A is getting passed through as context in B's decorator? Can you have a decorator validator?

(We have considered making A a child of B, but this doesn't really make sense for our application. I agree it would work, but it's not what we want.)

Это было полезно?

Решение

You can just override the initializer to validate that the context is passed:

class BDecorator
  def initialize(obj, options = {})
    raise "Must pass context" unless options.key? :context
    super
  end
end
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top