Class: JsonSti::InheritableSeeder

Inherits:
Object
  • Object
show all
Defined in:
lib/json_sti/inheritable_seeder.rb

Class Method Summary collapse

Class Method Details

.generate_valid_instance_of_class!(klass, only_required = false) ⇒ Object



63
64
65
# File 'lib/json_sti/inheritable_seeder.rb', line 63

def self.generate_valid_instance_of_class!(klass, only_required=false)
  populate_attrs_for_instance!(klass.new, only_required)
end

.populate_attrs_for_instance!(instance, only_required = false) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/json_sti/inheritable_seeder.rb', line 27

def self.populate_attrs_for_instance!(instance, only_required=false)
  klass = instance.class
  json_attrs = klass.class_variable_get(:@@json_attrs)
  return if json_attrs.blank?

  attrs = only_required ? klass.class_variable_get(:@@json_required) : klass.class_variable_get(:@@json_attrs).keys

  return if attrs.blank?

  attrs.each do |attr|
    type  = json_attrs[attr].values
    case type.first
      when "string"
        if type[1] && type[1] == "date"
          new_val = Faker::Date.between(from: 10.days.ago, to: Date.today)
        elsif type[1] && type[1] == "time"
          new_val = Faker::Time.between(from: DateTime.now - 1, to: DateTime.now)
        else
          new_val = Faker::Marketing.buzzwords
        end
      when "boolean"
        new_val = [true, false].sample
      when "integer"
        new_val = Integer(Faker::Number.within(range: 0..99))
      when "number"
        new_val = Faker::Number.decimal(l_digits:2, r_digits: 3)
    end

    instance.send((attr.to_s + "="), new_val)
  end

  instance.save!

  instance
end

.seed!(num_to_create = 3) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/json_sti/inheritable_seeder.rb', line 3

def self.seed!(num_to_create=3)
  relations_lookup = JsonSti::ClassMasterList.relations_lookup

  relations_lookup.each do |type, info|
    info[:members].each do |member|
      klass = "#{type.to_s.camelize}::#{member.to_s.camelize}".constantize
      instance = klass.create

      if !instance.valid?
        skip_sub_object_creation = self.fix_errors_on_instance_and_determine_next_step(instance)
        next if skip_sub_object_creation
      end

      p "Created a #{klass.to_s}"

      info[:relationships].each do |relationship|
        relations_lookup[relationship][:members].each do |relation_member|
          self.create_relationship_for_instance(instance, relationship, relation_member, num_to_create)
        end
      end
    end
  end
end