Sha256: d11e5bd84a71dcd1e34a2461a87248a4f813b2b84f21224a5f68869ee2904705

Contents?: true

Size: 1.53 KB

Versions: 4

Compression:

Stored size: 1.53 KB

Contents

class Trailblazer::Operation
  # :private:
  # This code is not beautiful, but could also be worse.
  # I'm expecting some of this to go to Uber, as we use this pattern everywhere.
  class Option
    def self.call(proc, &block)
      type = :proc

      option =
        if proc.is_a? Symbol
          type = :symbol
          ->(input, *_options) { call_method(proc, input, *_options) }
        elsif proc.is_a? Proc
          ->(input, *_options) { call_proc(proc, input, *_options) }
        elsif proc.is_a? Uber::Callable
          type = :callable
          ->(input, *_options) { call_callable(proc, input, *_options) }
        end

      yield type if block_given?
      option
    end

    def self.call_proc(proc, input, *options)
      proc.(*options)
    end

    def self.call_method(proc, input, *options)
      input.send(proc, *options)
    end

    def self.call_callable(callable, input, *options)
      callable.(*options)
    end

    # Call the option with keyword arguments. Ruby <= 2.0.
    class KW < Option
      def self.call_proc(proc, input, options)
        return proc.(options) if proc.arity == 1
        proc.(options, **options)
      end

      def self.call_method(proc, input, options)
        return input.send(proc, options) if input.method(proc).arity == 1 # TODO: remove this
        input.send(proc, options, **options)
      end

      def self.call_callable(callable, input, options)
        return callable.(options) if callable.method(:call).arity == 1
        callable.(options, **options)
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
trailblazer-operation-0.0.11 lib/trailblazer/operation/option.rb
trailblazer-operation-0.0.10 lib/trailblazer/operation/option.rb
trailblazer-operation-0.0.9 lib/trailblazer/operation/option.rb
trailblazer-operation-0.0.8 lib/trailblazer/operation/option.rb