Class: MKBrut::Ops::AddCSSImport

Inherits:
BaseOp
  • Object
show all
Defined in:
lib/mkbrut/ops/add_css_import.rb

Instance Method Summary collapse

Methods inherited from BaseOp

dry_run=, dry_run?, #dry_run?, fileutils_args, #fileutils_args

Constructor Details

#initialize(project_root:, import:) ⇒ AddCSSImport

Returns a new instance of AddCSSImport.



2
3
4
5
# File 'lib/mkbrut/ops/add_css_import.rb', line 2

def initialize(project_root:, import:)
  @file   = project_root / "app" / "src" / "front_end" / "css" / "index.css"
  @import = import
end

Instance Method Details

#callObject



7
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
# File 'lib/mkbrut/ops/add_css_import.rb', line 7

def call
  if dry_run?
    puts "Would add import '#{@import}'; to '#{@file}'"
    return
  end

  contents = File.read(@file).split(/\n/)

  inserted_import          = false
  previous_line_was_import = false
  new_contents = []
  contents.each do |line|
    if line =~ /^\s*@import\s+["']/
      previous_line_was_import = true
      new_contents << line
    else
      if previous_line_was_import && !inserted_import
        new_contents << "@import '#{@import}';"
        inserted_import = true
      end
      previous_line_was_import = false
      new_contents << line
    end
  end
  if !inserted_import && previous_line_was_import
    new_contents << "@import \"#{@import}\";"
    inserted_import = true
  end
  if !inserted_import
    raise "Did not find any other @imports in '#{@file}' - was expecting at least one to exist"
  end
  File.open(@file, "w") do |file|
    file.puts new_contents.join("\n")
  end
end