Sha256: 0bda8a10254f0d5dd799717e3410f9aee0112d2cd56b587342a05f9db52a2197

Contents?: true

Size: 1.27 KB

Versions: 1

Compression:

Stored size: 1.27 KB

Contents

require "json"
require "active_support/core_ext/hash/indifferent_access"

module SerialSpec

  class ParsedBody

    attr_reader :raw_body
    attr_reader :selector

    def initialize(body)
      @selector = []
      @raw_body = JSON.parse(body)
    end

    def self.add_selector(*methuds)
      methuds.each do |methud|
        class_eval <<-METHOD
          def #{methud.to_s}(*args)
            selector.push([#{methud.to_sym}, args])
            self
          end
        METHOD
      end
    end

    add_selector :first, :last, :[]

    def [](*args)
      selector.push([:[], *args])
      self
    end

    def first(*args)
      selector.push([:first])
      self
    end

    def last(*args)
      selector.push([:last])
      self
    end

    def execute
      copy = selector.clone
      selector.clear
      copy.inject(raw_body) do |remainder, method_and_args|
        begin
          methud, *args = method_and_args
          if remainder.kind_of?(Hash)
            remainder.with_indifferent_access.send methud, *args
          else
            remainder.send methud, *args
          end
        rescue NoMethodError => ex
          raise ArgumentError, "could not find '#{methud.inspect}' \nfor:\n '#{remainder.inspect}' \nin\n #{raw_body}"
        end
      end
    end

  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
serial-spec-0.2.1 lib/serial_spec/parsed_body.rb