Sha256: e4a2f9d637fc06e207f413d51012379a6e2c96e21b6ec67381cf01059a5eebf8

Contents?: true

Size: 1.16 KB

Versions: 1

Compression:

Stored size: 1.16 KB

Contents

module Stairs
  module Util
    module FileMutation
      class << self
        def replace_or_append(pattern, string, filename)
          if File.exist? filename
            contents = File.read filename
            if contents =~ pattern
              contents.sub! pattern, string
              write contents, filename
              return
            end
          end

          write_line string, filename
        end

        def remove(pattern, filename)
          return unless File.exist? filename

          contents = File.read filename
          return unless contents =~ pattern

          contents.slice!(pattern)
          write contents, filename
        end

        def write_line(string, filename)
          File.open filename, 'a+' do |file|
            # ensure file ends with newline before appending
            last_line = file.each_line.reduce('') { |_m, l| l }
            file.puts '' unless last_line == '' || last_line =~ /(.*)\n/

            file.puts string
          end
        end

        def write(string, filename)
          File.open filename, 'w+' do |file|
            file.puts string
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
stairs-0.10.0 lib/stairs/util/file_mutation.rb