Module: SvelteOnRails::Installer::Javascript
- Defined in:
- lib/svelte_on_rails/installer/javascript.rb
Class Method Summary collapse
-
.append_import_statement(file_path, package_name_for_test_existence, import_statement) ⇒ Object
check if import statement already exists and, if not, append it after the last import statement of that file.
Class Method Details
.append_import_statement(file_path, package_name_for_test_existence, import_statement) ⇒ Object
check if import statement already exists and, if not, append it after the last import statement of that file
8 9 10 11 12 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 45 46 47 48 49 50 51 |
# File 'lib/svelte_on_rails/installer/javascript.rb', line 8 def self.append_import_statement(file_path, package_name_for_test_existence, import_statement) # Read the file content content = File.read(file_path) # Split content into lines lines = content.lines already_exist = [] lines.each do |line| if line.match(/^\s*import\s+.*['"]#{package_name_for_test_existence}['";].*$/) already_exist.push(line) end end if already_exist.present? puts "skipping: #{import_statement} already exists in #{File.basename(file_path)}, found: «#{already_exist.join(' // ').strip}»." else # Find the index of the last import statement last_import_index = -1 lines.each_with_index do |line, index| if line.match?(/^\s*import\s+.*$/) last_import_index = index end end # Insert the import statement after the last import if last_import_index >= 0 lines.insert(last_import_index + 1, import_statement) else # If no import statements, add at the beginning lines.unshift(import_statement) end # Write the modified content back to the file begin File.write(file_path, lines.map{|l|l.gsub(/\n/, '')}.join("\n")) puts "Successfully inserted «#{import_statement}» into '#{file_path}' on line #{last_import_index + 2}." rescue => e raise "Error writing to #{file_path} => «#{e.}»" end end end |