Sha256: 18a4d4959b1da9f384e716f045a93abc33f94680067794bdf961c26a7137eb00

Contents?: true

Size: 1.37 KB

Versions: 5

Compression:

Stored size: 1.37 KB

Contents

require 'faker'

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.subtype
          Array.new(3) do
            mock_value(field.subtype)
          end
        elsif !field.fields.empty?
          # recursively mock values
          mock_fields(field)
        else
          case field.name
          when "int", :int
            Random.new.rand(10000000)
          when "string", :string
            Faker::Hacker.noun
          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.6.0 lib/service_contract/mock.rb
service_contract-0.5.1 lib/service_contract/mock.rb
service_contract-0.5.0 lib/service_contract/mock.rb
service_contract-0.4.1 lib/service_contract/mock.rb
service_contract-0.4.0 lib/service_contract/mock.rb