Class: StructuredNoise::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/structured_noise/generator.rb

Defined Under Namespace

Classes: TypeGenerator

Constant Summary collapse

MAGIC_BYTE =
[0].pack("C").freeze

Instance Method Summary collapse

Constructor Details

#initialize(schema:, base64: false, messages_per_second: 0) ⇒ Generator

Returns a new instance of Generator.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/structured_noise/generator.rb', line 11

def initialize(schema:, base64: false, messages_per_second: 0)
  @schema_file_name = schema
  @output_base64 = base64
  @messages_per_second = messages_per_second
  @schemas = {}

  AvroPinions.configure({ wire_format: :single_object })

  @message = Class.new(AvroPinions::Message) do
    def initialize(avro_schema, data)
      @avro_schema = avro_schema
      @data = data
    end

    def record
      @data
    end

    def avro_schema
      @avro_schema
    end
  end
end

Instance Method Details

#generate_outputObject



43
44
45
46
47
48
49
50
51
# File 'lib/structured_noise/generator.rb', line 43

def generate_output
  with_timing do
    msg = @message.new(@avro_schema, generate_random_fields).encode
    if @output_base64
      msg = Base64.encode64(msg)
    end
    puts msg
  end
end

#generate_random_fieldsObject



53
54
55
56
57
58
59
# File 'lib/structured_noise/generator.rb', line 53

def generate_random_fields
  @avro_schema.fields.inject(Hash.new) do |hash, field|
    type_gen = TypeGenerator.new(field)
    hash[field.name] = type_gen.generate_value
    hash
  end
end

#load_schemaObject



35
36
37
38
39
40
41
# File 'lib/structured_noise/generator.rb', line 35

def load_schema
  json = JSON.parse(File.read(@schema_file_name))
  @schema_name = json["name"]
  @namespace = json["namespace"] || ""

  @avro_schema = Avro::Schema.real_parse(json)
end

#with_timingObject



61
62
63
64
65
66
67
68
# File 'lib/structured_noise/generator.rb', line 61

def with_timing
  while true
    yield
    if(@messages_per_second)
      sleep (1 / @messages_per_second)
    end
  end
end