Sha256: 7f5bf6069777627c0d9d5cf48270c8e9e0d3bbcf40faab0e787b8a71f3de6074

Contents?: true

Size: 1.38 KB

Versions: 5

Compression:

Stored size: 1.38 KB

Contents

require 'random-word'

module ServiceContract
  class Mock
    class << self
      # generates fake data that adheres to the types defined in the service contract
      def generate!(version)
        mock_fields(type(version))
      end

      private

      def type(version)
        raise "not_implemented"
      end

      # can set up custom generators by field name
      #   should be a hash of <field_name> => <lambda>
      def customizations
        {}
      end

      def mock_fields(type)
        {}.tap do |res|
          type.fields.each do |parameter|
            if customizations.key?(parameter.name)
              res[parameter.name] = customizations[parameter.name].call
            else
              res[parameter.name] = mock_value(parameter.type)
            end
          end
        end
      end

      def mock_value(field)
        if field.array?
          Array.new(3) do
            mock_value(field.subtype)
          end
        elsif field.complex?
          # recursively mock values
          mock_fields(field)
        else
          case field.name
          when "int", :int
            Random.new.rand(10000000)
          when "string", :string
            RandomWord.nouns.next
          when "float", :float
            Random.new.rand(10000.0)
          when "boolean", :boolean
            [true, false].sample
          end
        end        
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
service_contract-0.2.1 lib/service_contract/mock.rb
service_contract-0.2.0 lib/service_contract/mock.rb
service_contract-0.1.1 lib/service_contract/mock.rb
service_contract-0.1.0 lib/service_contract/mock.rb
service_contract-0.0.10 lib/service_contract/mock.rb