3

Is it possible to delegate a function or series of functions to one of multiple other objects based on conditional logic?

Ex:

class Item
    has_one :thing
    has_one :other_thing

    delegate :foo,
             :bar
             to: :[thing or other_thing]
end

In this case, I would want the actions foo and bar to either be delegated to the thing, or the other thing based on some conditional logic.

Possibly related: Active Record with Delegate and conditions

Community
  • 1
  • 1
ThunderGuppy
  • 189
  • 1
  • 11

2 Answers2

5

Yes.

in addition to other objects, functions can be delegated to other functions.

Ex:

class Item
  has_one :thing
  has_one :other_thing

  delegate :foo,
           :bar
           to: :correct_thing

  def correct_thing
    [conditional] ? thing : other_thing
  end
end
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
ThunderGuppy
  • 189
  • 1
  • 11
0

Something like below:

class Item
  has_one :thing
  has_one :other_thing

  delegate :foo,
           :bar
           to: :thing if: thing_condition?

  delegate :foo,
           :bar
           to: :otherthing if: otherthing_condition?
end
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
Sapna Jindal
  • 412
  • 3
  • 11