Sha256: 9f6e22962c89d66680d9434cb75d6f618d5423e564edd7952d16bf4c8bfb6545

Contents?: true

Size: 1.48 KB

Versions: 1

Compression:

Stored size: 1.48 KB

Contents

module Bogus
  class Interaction < Struct.new(:method, :args, :return_value, :error, :has_result)
    def initialize(method, args, &block)
      self.method = method
      self.args = args

      if block_given?
        evaluate_return_value(block)
        self.has_result = true
      end
    end

    def ==(other)
      method == other.method && same_args?(other) && same_result?(other)
    end

    def any_args?
      [AnyArgs] == args
    end

    def args
      args = super.map { |arg| remove_default_values_from_hash(arg) }
      args.reject { |arg| arg.eql?(DefaultValue) }
    end

    private

    def same_args?(other)
      return true if any_args? || other.any_args?

      other_args = normalize_other_args(args, other.args)
      return false unless args.size == other_args.size
      args.zip(other_args).all?{|a1, a2| a1 == a2 || a2 == a1}
    end

    def normalize_other_args(args, other_args)
      if args.last.is_a?(Hash) && !other_args.last.is_a?(Hash)
        other_args + [{}]
      else
        other_args
      end
    end

    def same_result?(other)
      return true unless has_result && other.has_result
      return_value == other.return_value && error == other.error
    end

    def evaluate_return_value(block)
      self.return_value = block.call
    rescue => e
      self.error = e.class
    end

    def remove_default_values_from_hash(arg)
      if arg.is_a?(Hash)
        arg.reject { |_, val| val.eql?(DefaultValue) }
      else
        arg
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
bogus-0.1.0 lib/bogus/interaction.rb