Method: Hanami::Utils::Files.remove_block

Defined in:
lib/hanami/utils/files.rb

.remove_block(path, target) ⇒ Object

Removes ‘target` block from `path`

Examples:

require "hanami/utils/files"

puts File.read("app.rb")

# class App
#   configure do
#     root __dir__
#   end
# end

Hanami::Utils::Files.remove_block("app.rb", "configure")

puts File.read("app.rb")

# class App
# end

Parameters:

  • path (String, Pathname)

    the path to file

  • target (String)

    the target block to remove

Raises:

  • (Errno::ENOENT)

    if the path doesn’t exist

  • (ArgumentError)

    if ‘target` cannot be found in `path`

Since:

  • 1.1.0

[View source]

311
312
313
314
315
316
317
318
319
320
321
322
323
# File 'lib/hanami/utils/files.rb', line 311

def self.remove_block(path, target)
  content  = ::File.readlines(path)
  starting = index(content, path, target)
  line     = content[starting]
  size     = line[/\A[[:space:]]*/].bytesize
  closing  = (" " * size) + (/{/.match?(target) ? "}" : "end")
  ending   = starting + index(content[starting..], path, closing)

  content.slice!(starting..ending)
  write(path, content)

  remove_block(path, target) if match?(content, target)
end