Class: MKBrut::Segments::BareBones::InsertCustomElement
- Inherits:
-
Ops::BaseOp
- Object
- Ops::BaseOp
- MKBrut::Segments::BareBones::InsertCustomElement
- Defined in:
- lib/mkbrut/segments/bare_bones.rb
Instance Method Summary collapse
- #call ⇒ Object
-
#initialize(project_root:, element_class_name:) ⇒ InsertCustomElement
constructor
A new instance of InsertCustomElement.
Methods inherited from Ops::BaseOp
dry_run=, dry_run?, #dry_run?, fileutils_args, #fileutils_args
Constructor Details
#initialize(project_root:, element_class_name:) ⇒ InsertCustomElement
Returns a new instance of InsertCustomElement.
97 98 99 100 |
# File 'lib/mkbrut/segments/bare_bones.rb', line 97 def initialize(project_root:, element_class_name:) @file = project_root / "app" / "src" / "front_end" / "js" / "index.js" @element_class_name = element_class_name end |
Instance Method Details
#call ⇒ Object
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 |
# File 'lib/mkbrut/segments/bare_bones.rb', line 101 def call if dry_run? puts "Would insert custom element '#{@element_class_name}' into #{@file}" return end inserted = false new_source = [] File.read(@file).split("\n").each do |line| regexp = /^document\.addEventListener\(\"DOMContentLoaded\"/ if line.match?(regexp) new_source << %{import #{@element_class_name} from "./#{@element_class_name}"} new_source << line new_source << %{ #{@element_class_name}.define()} inserted = true else new_source << line end end if !inserted raise "Could not find a place to insert code in '#{@file}'. Trying to find a line that matches this regular expression:\n\n#{regexp.inspect}" end File.open(@file, "w") do |file| file.puts new_source.join("\n") end end |