Class: Pineapples::Actions::InsertIntoFile

Inherits:
EmptyDirectory show all
Defined in:
lib/pineapples/actions/insert_into_file.rb

Constant Summary

Constants inherited from Action

Action::STATUS_COLORS

Instance Attribute Summary collapse

Attributes inherited from EmptyDirectory

#skip, #target

Attributes inherited from Action

#colors, #generator, #options

Instance Method Summary collapse

Methods inherited from EmptyDirectory

#exists?

Methods inherited from Action

colors, inherited, #skip?, status_color

Constructor Details

#initialize(generator, target, new_content, options) ⇒ InsertIntoFile



63
64
65
66
67
68
69
70
71
# File 'lib/pineapples/actions/insert_into_file.rb', line 63

def initialize(generator, target, new_content, options)
  super(generator, target, {verbose: true}.merge(options))

  @behaviour = @options.key?(:after) ? :after : :before
  @flag = @options.delete(@behaviour)

  @new_content = new_content.is_a?(Proc) ? new_content.call : new_content
  @flag = Regexp.escape(@flag) if !@flag.is_a?(Regexp)
end

Instance Attribute Details

#behaviourObject (readonly)

Returns the value of attribute behaviour.



54
55
56
# File 'lib/pineapples/actions/insert_into_file.rb', line 54

def behaviour
  @behaviour
end

#flagObject (readonly)

Returns the value of attribute flag.



54
55
56
# File 'lib/pineapples/actions/insert_into_file.rb', line 54

def flag
  @flag
end

#new_contentObject (readonly)

Returns the value of attribute new_content.



54
55
56
# File 'lib/pineapples/actions/insert_into_file.rb', line 54

def new_content
  @new_content
end

Instance Method Details

#invoke!Object



73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/pineapples/actions/insert_into_file.rb', line 73

def invoke!
  say_status status(:invoke)

  content = if @behavior == :after
              '\0' + replacement
            else
              replacement + '\0'
            end

  regexp = /#{flag}/

  replace!(regexp, content, options[:force])
end

#revoke!Object



87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/pineapples/actions/insert_into_file.rb', line 87

def revoke!
  say_status status(:revoke)

  if @behavior == :after
    content = '\1\2'
    regexp = /(#{flag})(.*)(#{Regexp.escape(new_content)})/m
  else
    content = '\2\3'
    regexp = /(#{Regexp.escape(new_content)})(.*)(#{flag})/m
  end

  replace!(regexp, content, true)
end