Module: Filander::InjectIntoFile

Includes:
Base
Included in:
Filander
Defined in:
lib/filander/actions/inject_into_file.rb

Instance Method Summary collapse

Methods included from Base

#create_directory_for, #entries, #join_destination, #join_source, #report, #with_report

Instance Method Details

#inject_into_file(destination, *args, &block) ⇒ Object



5
6
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
# File 'lib/filander/actions/inject_into_file.rb', line 5

def inject_into_file(destination, *args, &block)
  filename = join_destination(destination)

  if block_given?
    data, config = block.call, args.shift
  else
    data, config = args.shift, args.shift
  end

  position = config[:after] ? :after : :before
  flag     = config[position]
  flag     = Regexp.escape(flag) unless flag.is_a?(Regexp)

  replacement = if position == :after
                  '\0' + data
                else
                  data + '\0'
                end

  present = if position == :after
              /#{flag}#{Regexp.escape data}/
            else
              /#{Regexp.escape data}#{flag}/
            end

  content = File.read(filename) if File.file?(filename)
  content ||= ''
  content.gsub!(/#{flag}/, replacement) unless content =~ present

  with_report destination, content do
    File.open(filename, "w") { |file| file << content }
  end
end