Class: RailsEngineToolkit::RoutesRewriter

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_engine_toolkit/routes_rewriter.rb

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ RoutesRewriter

Returns a new instance of RoutesRewriter.



5
6
7
# File 'lib/rails_engine_toolkit/routes_rewriter.rb', line 5

def initialize(path)
  @path = Pathname(path)
end

Instance Method Details

#add_mount(engine_class:, mount_path:) ⇒ Object

Raises:



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/rails_engine_toolkit/routes_rewriter.rb', line 9

def add_mount(engine_class:, mount_path:)
  raise ValidationError, "Routes file not found: #{@path}" unless @path.file?

  content = @path.read
  inspector = RouteInspector.new(content)
  return false if inspector.includes_mount?(engine_class, mount_path)

  mount_line = %(  mount #{engine_class}::Engine, at: "#{mount_path}"\n)

  updated = content.sub(/^(\s*Rails\.application\.routes\.draw do\s*\n)/) do |match|
    "#{match}#{mount_line}"
  end
  raise CommandError, "Could not find Rails.application.routes.draw block in #{@path}" if updated == content

  @path.write(updated)
  true
end

#remove_mount(engine_class:, mount_path:) ⇒ Object

Raises:



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rails_engine_toolkit/routes_rewriter.rb', line 27

def remove_mount(engine_class:, mount_path:)
  raise ValidationError, "Routes file not found: #{@path}" unless @path.file?

  original = @path.read
  lines = original.lines.reject do |line|
    mount_line?(line, engine_class: engine_class, mount_path: mount_path)
  end
  updated = lines.join
  changed = updated != original
  @path.write(updated) if changed
  changed
end