class ServiceContract::Mock

Public Class Methods

generate!(version) click to toggle source

generates fake data that adheres to the types defined in the service contract

# File lib/service_contract/mock.rb, line 7
def generate!(version)
  mock_fields(type(version))
end

Private Class Methods

customizations() click to toggle source

can set up custom generators by field name

should be a hash of <field_name> => <lambda>
# File lib/service_contract/mock.rb, line 19
def customizations
  {}
end
mock_fields(type) click to toggle source
# File lib/service_contract/mock.rb, line 23
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
mock_value(field) click to toggle source
# File lib/service_contract/mock.rb, line 35
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
type(version) click to toggle source
# File lib/service_contract/mock.rb, line 13
def type(version)
  raise "not_implemented"
end