Module: FixtureBot

Defined in:
lib/fixture_bot.rb,
lib/fixture_bot/helpers.rb,
lib/fixture_bot/version.rb,
lib/fixture_bot/minitest.rb,
lib/fixture_bot/table_loader.rb,
lib/fixture_bot/fixture_creator.rb

Defined Under Namespace

Modules: FixtureCreator, Helpers, Preload Classes: TableLoader

Constant Summary collapse

VERSION =
"0.5.0"

Class Method Summary collapse

Class Method Details

.after_load_fixtures(&block) ⇒ Object



17
18
19
# File 'lib/fixture_bot.rb', line 17

def after_load_fixtures(&block)
  @after_load_fixtures = block
end

.cached_fixturesObject



51
52
53
54
55
56
# File 'lib/fixture_bot.rb', line 51

def cached_fixtures
  connection.query(<<-SQL).first
    CREATE TABLE IF NOT EXISTS __fixture_bot_cache_v1(fixtures_time timestamptz, fixtures_dump bytea);
    SELECT fixtures_time, fixtures_dump FROM __fixture_bot_cache_v1
  SQL
end

.caching_max_mtime_fixtures(dump_record_ids) ⇒ Object



58
59
60
61
62
# File 'lib/fixture_bot.rb', line 58

def caching_max_mtime_fixtures(dump_record_ids)
  connection.execute <<-SQL
    INSERT INTO __fixture_bot_cache_v1 VALUES ('#{max_mtime_fixtures.iso8601(6)}', '#{Base64.encode64(dump_record_ids)}')
  SQL
end

.colored_output(text) ⇒ Object



80
81
82
# File 'lib/fixture_bot.rb', line 80

def colored_output(text)
  puts "\e[33m#{text}\e[0m"
end

.connectionObject



76
77
78
# File 'lib/fixture_bot.rb', line 76

def connection
  ::ActiveRecord::Base.connection
end

.define_fixture_helpersObject



72
73
74
# File 'lib/fixture_bot.rb', line 72

def define_fixture_helpers
  ::FactoryBot::SyntaxRunner.include(::FixtureBot::Helpers)
end

.load_modelsObject



64
65
66
67
68
69
70
# File 'lib/fixture_bot.rb', line 64

def load_models
  return unless defined?(Rails)

  Dir[Rails.application.root.join("app/models/**/*.rb")].each do |file|
    require_dependency file
  end
end

.max_mtime_fixturesObject



40
41
42
43
44
45
46
47
48
49
# File 'lib/fixture_bot.rb', line 40

def max_mtime_fixtures
  @max_mtime_fixtures ||=
    FactoryBot.definition_file_paths.flat_map { |path|
      directory_path = File.expand_path(path)

      if File.directory?(directory_path)
        Dir[File.join(directory_path, "**", "*.rb")].map { |file| File.mtime(file) }
      end
    }.compact.max.round(6)
end

.runObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/fixture_bot.rb', line 21

def run
  cached_mtime, cached_record_ids = cached_fixtures
  if cached_mtime && cached_mtime == max_mtime_fixtures
    colored_output "Cache load fixtures"

    FixtureBot::FixtureCreator.record_ids = Marshal.load(Base64.decode64(cached_record_ids))
    define_fixture_helpers
  else
    colored_output "Full load fixtures"

    ActiveRecord::Tasks::DatabaseTasks.truncate_all
    load_models
    define_fixture_helpers
    FixtureBot::FixtureCreator.load_to_db
    @after_load_fixtures&.call
    caching_max_mtime_fixtures(Marshal.dump(FixtureBot::FixtureCreator.record_ids))
  end
end