DEV Community

Discussion on: API and Provider methodology

Collapse
 
thermatix profile image
Martin Becker

If someone is interested in a functional pipline example:

module Pipeline
  def pipline_for(action, *pipes)
    (@listing ||= {})[action] = pipes
    define_singleton_method(action) do |*args|
      run_pipline_for(action, *args)
    end
  end

  def run_pipline_for(action, *args)
    @listing[action].inject(args) do |result, (item, custom_action)|
      item.send(custom_action || action, *result)
    end
  end
end

module Formatters
  class Input
    class << self
      def action(*args)
        puts "Formatters::Input.action"

        args
      end

      def other_action(*args)
        puts "Formatters::Input.other_action"

        args
      end
    end
  end

  class Output
    class << self
      def action(*args)
        puts "Formatters::Output.action"

        args
      end
    end
  end
end

class Provider
  class << self
    def get_remote_data(*args)
      puts "Provider.get_remote_data"

      args
    end

    def other_action(*args)
      puts "Provider.other_action"

      args
    end
  end
end

class Processor
  class << self
    def action(*args)
      puts "Processor.action"

      args
    end

    def custom_processor(*args)
      puts "Processor.custom_processor"

      args
    end
  end
end

class API
  extend Pipeline

  pipline_for :action, Formatters::Input, [Provider, :get_remote_data], Processor, Formatters::Output
  pipline_for :other_action, Formatters::Input, Provider, [Processor, :custom_processor], [Formatters::Output, :action]
end

puts API.action('Hello World')
puts API.other_action('Goodbye World')