Class: ProtoFactory::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/proto_factory/builder.rb

Class Method Summary collapse

Class Method Details

.build(factory_name) ⇒ Object



7
8
9
10
11
12
# File 'lib/proto_factory/builder.rb', line 7

def build(factory_name)
  factory_class ||= Object.const_get(find(factory_name))
  proto_object = factory_class.new
   = generate_types(factory_class)
  set_data(proto_object, , factory_class)
end

.find(factory_name) ⇒ Object



70
71
72
# File 'lib/proto_factory/builder.rb', line 70

def find(factory_name)
  ProtoFactory.configuration.factories[factory_name.to_sym]
end

.generate_types(factory_class) ⇒ Object



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

def generate_types(factory_class)
   = {}
  field_desc = factory_class.descriptor.to_a
  field_desc.each do |field|
    ["#{field.name}"] = field.type
  end
  
end

.set_all_messages(proto_object, factory_class, name) ⇒ Object



46
47
48
49
50
51
# File 'lib/proto_factory/builder.rb', line 46

def set_all_messages(proto_object, factory_class, name)
  message_class = submsg_to_class(factory_class.descriptor.lookup("#{name}").submsg_name)
  nested_collection = generate_types(message_class)
  nested_proto_object = message_class.new
  proto_object["#{name}"] = set_data(nested_proto_object, nested_collection, message_class)
end

.set_data(proto_object, metadata, factory_class) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/proto_factory/builder.rb', line 14

def set_data(proto_object, , factory_class)
  .each do |name, data_type|
    case data_type
    when :message
      set_all_messages(proto_object, factory_class, name)
    when :enum
      set_random_enum(proto_object, factory_class, name)
    when :int32, :int64
      proto_object["#{name}"] = ::Faker::Number.number(4).to_i
    when :string
      proto_object["#{name}"] = ::Faker::Hacker.verb
    when :bool
      proto_object["#{name}"] = ::Faker::Boolean.boolean(0.5)
    else
      proto_object["#{name}"] = "Found a weird #{data_type} data type, yo."
    end
  end
  proto_object
end

.set_random_enum(proto_object, factory_class, name) ⇒ Object



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

def set_random_enum(proto_object, factory_class, name)
  enum_class = submsg_to_class(factory_class.descriptor.lookup("#{name}").submsg_name)
  enum_options = enum_class.descriptor.to_h
  size = enum_options.size.to_i
  random_number = rand(1..size)
  proto_object["#{name}"] = random_number
end

.submsg_to_class(submsg_name) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/proto_factory/builder.rb', line 34

def submsg_to_class(submsg_name)
  array_of_words = submsg_name.split('.')
  class_string = array_of_words.map do |word|
    if word.match?(/[A-Z]/)
      word
    else
      word.split('_').collect(&:capitalize).join
    end
  end.join('::') # thanks I hate it
  Object.const_get(class_string)
end