Class: MigrationQueries::FileWriter

Inherits:
Object
  • Object
show all
Defined in:
lib/migration_queries/file_writer.rb

Overview

FileWriter is responsible for writing SQL queries to a specified file.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path, sql_queries: []) ⇒ FileWriter

Returns a new instance of FileWriter.



8
9
10
11
# File 'lib/migration_queries/file_writer.rb', line 8

def initialize(file_path, sql_queries: [])
  @file_path = file_path
  @sql_queries = sql_queries
end

Instance Attribute Details

#file_pathObject (readonly)

Returns the value of attribute file_path.



6
7
8
# File 'lib/migration_queries/file_writer.rb', line 6

def file_path
  @file_path
end

#sql_queriesObject (readonly)

Returns the value of attribute sql_queries.



6
7
8
# File 'lib/migration_queries/file_writer.rb', line 6

def sql_queries
  @sql_queries
end

Instance Method Details

#write_to_fileObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/migration_queries/file_writer.rb', line 13

def write_to_file
  return if sql_queries.empty?

  File.open(file_path, "r+") do |file|
    content = file.readlines
    filtered_content = []
    inside_block = false

    content.each do |line|
      if line.strip == "=begin Migration Queries"
        inside_block = true
        next
      elsif line.strip == "=end"
        inside_block = false
        next
      end
      filtered_content << line unless inside_block
    end

    file.rewind
    file.truncate(0)
    filtered_content.each { |line| file.puts line }
    file.puts "=begin Migration Queries"
    sql_queries.each do |query|
      file.puts query
    end
    file.puts "=end"
    file.flush
  end
rescue StandardError => e
  puts "Error writing to file #{file_path}: #{e.message}"
end