Sha256: 0868b6f35be134c0af10b59d5d04835000f3002dd36c5c0795b0ed340d4b4781

Contents?: true

Size: 1.15 KB

Versions: 3

Compression:

Stored size: 1.15 KB

Contents

require 'sanford-protocol'
require 'and-son/response'

module AndSon

  class StoredResponses

    def initialize
      @hash = Hash.new{ |h, k| h[k] = Stub.new }
    end

    def add(name, &block)
      @hash[name].tap{ |s| s.set_default_proc(&block) }
    end

    def get(name, params)
      response = @hash[name].call(params)
      AndSon::Response.new(response)
    end

    def remove(name)
      @hash.delete(name)
    end

    def remove_all
      @hash.clear
    end

    class Stub
      attr_reader :hash

      def initialize
        @default_proc = proc{ |r| r.data = Hash.new }
        @hash = {}
      end

      def set_default_proc(&block)
        @default_proc = block if block
      end

      def with(params, &block)
        @hash[params] = block
        self
      end

      def call(params)
        block = @hash[params] || @default_proc
        if block.arity == 0 || block.arity == -1
          default_response.tap{ |r| r.data = block.call }
        else
          default_response.tap{ |r| block.call(r) }
        end
      end

      private

      def default_response
        Sanford::Protocol::Response.new(200, {})
      end
    end

  end

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
and-son-0.9.1 lib/and-son/stored_responses.rb
and-son-0.9.0 lib/and-son/stored_responses.rb
and-son-0.8.0 lib/and-son/stored_responses.rb