conditional chaining in ruby

后端 未结 9 2181
一生所求
一生所求 2020-12-13 20:30

Is there a good way to chain methods conditionally in Ruby?

What I want to do functionally is

if a && b && c
 my_object.some_method_b         


        
9条回答
  •  长情又很酷
    2020-12-13 21:13

    Sample class to demonstrate chaining methods that return a copied instance without modifying the caller. This might be a lib required by your app.

    class Foo
      attr_accessor :field
        def initialize
          @field=[]
        end
        def dup
          # Note: objects in @field aren't dup'ed!
          super.tap{|e| e.field=e.field.dup }
        end
        def a
          dup.tap{|e| e.field << :a }
        end
        def b
          dup.tap{|e| e.field << :b }
        end
        def c
          dup.tap{|e| e.field << :c }
        end
    end
    

    monkeypatch: this is what you want to add to your app to enable conditional chaining

    class Object
      # passes self to block and returns result of block.
      # More cumbersome to call than #chain_if, but useful if you want to put
      # complex conditions in the block, or call a different method when your cond is false.
      def chain_block(&block)
        yield self
      end
      # passes self to block
      # bool:
      # if false, returns caller without executing block.
      # if true, return result of block.
      # Useful if your condition is simple, and you want to merely pass along the previous caller in the chain if false.
      def chain_if(bool, &block)
        bool ? yield(self) : self
      end
    end
    

    Sample usage

    # sample usage: chain_block
    >> cond_a, cond_b, cond_c = true, false, true
    >> f.chain_block{|e| cond_a ? e.a : e }.chain_block{|e| cond_b ? e.b : e }.chain_block{|e| cond_c ? e.c : e }
    => #
    # sample usage: chain_if
    >> cond_a, cond_b, cond_c = false, true, false
    >> f.chain_if(cond_a, &:a).chain_if(cond_b, &:b).chain_if(cond_c, &:c)
    => #
    
    # The chain_if call can also allow args
    >> obj.chain_if(cond) {|e| e.argified_method(args) }
    

提交回复
热议问题