Module: FileMutate::InsertContent::ClassMethods

Defined in:
lib/file_mutate/insert_content.rb

Instance Method Summary collapse

Instance Method Details

#insert_into(file_name, *args, &block) ⇒ Object

insert_into ‘my_file.txt’, :after => ‘Blip’, :content => ‘Hello insert_into ’my_file.txt’, ‘Hello’, :after => ‘Blip’ insert_into ‘my_file.txt’, :after => ‘Blip’ do

'Hello'

end



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
38
39
40
41
42
43
44
45
# File 'lib/file_mutate/insert_content.rb', line 13

def insert_into file_name, *args, &block
  options = last_option args
  content = insertion_content options, *args, &block

  # no content to insert?
  return nil if content.blank? 

  file = begin
           get_file(file_name)
         rescue
           return nil
         end

  # already inserted?
  return nil if !options[:repeat] && file.has_content?(content)

  # find where to insert
  place, marker = if options[:before] 
                    [ :before, options[:before] ]
                  elsif options[:before_last]
                    [ :before_last, options[:before_last] ]
                  else
                    [ :after, options[:after] ]
                  end 

  return nil if !file.has_content?(marker)

  # do mutation
  res = file.mutate marker, place do
    content
  end
  res
end

#insertion_content(options = {}, *args, &block) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/file_mutate/insert_content.rb', line 47

def insertion_content options = {}, *args, &block
  case args.first
  when String
    args.first
  when Hash
    options[:content] || (yield if block)      
  else
    return yield if block
    raise ArgumentError, "You must supply content to insert, either as a String before the options hash, a :content option or a block" 
  end     
end