Victor
Victor

Reputation: 13368

Recursive method with condition

Using Ruby 2.0. Here's my code:

module Test
  class A
    def initialize(x)
      @x = x
      foo
    end

    def foo
      p @x
      update(@x) # only if it's a Test::C object or called from Test::C
    end
  end
end

module Test
  class B < A
    def foo
      @x += 2
      super
    end
  end
end

module Test
  class C < A
    def foo
      @x += 1
      super
    end
  end
end

def update(x)
  if x > 100
    Test::B.new(x)
  else
    Test::C.new(x)
  end
end

x = 100
update(x)

Here's what I am trying to achieve:

In Test::A#foo, update(@x) should be called only if it were called from Test::C#foo or it's a Test::C object.

The first time update(x) is called, x = 100, so the operation should +1 and then move on to Test::B#foo once. How do I achieve this?

Upvotes: 0

Views: 45

Answers (1)

tadman
tadman

Reputation: 211560

The parent class should not have to care about subclasses. This design you have here implies it needs to know, which is broken and over-complicates things.

In any case, if you do need to trap certain cases:

case (self)
when Test::A, Test::B
  # ... Do stuff
  update(@x)
end

If Test::A and Test::B care about that operation, they should call it when necessary:

def foo
  @x += 1
  super
  update(x)
end

Upvotes: 1

Related Questions