Class: Thor::Actions::InjectIntoFile

Inherits:
EmptyDirectory show all
Defined in:
lib/thor/actions/inject_into_file.rb

Overview

:nodoc:

Instance Attribute Summary collapse

Attributes inherited from EmptyDirectory

#base, #config, #destination, #given_destination, #relative_destination

Instance Method Summary collapse

Methods inherited from EmptyDirectory

#exists?

Constructor Details

#initialize(base, destination, data, config) ⇒ InjectIntoFile

Returns a new instance of InjectIntoFile.



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/thor/actions/inject_into_file.rb', line 39

def initialize(base, destination, data, config)
  super(base, destination, {verbose: true}.merge(config))

  @behavior, @flag = if @config.key?(:after)
    [:after, @config.delete(:after)]
  else
    [:before, @config.delete(:before)]
  end

  @replacement = data.is_a?(Proc) ? data.call : data
  @flag = Regexp.escape(@flag) unless @flag.is_a?(Regexp)
end

Instance Attribute Details

#behaviorObject (readonly)

Returns the value of attribute behavior.



37
38
39
# File 'lib/thor/actions/inject_into_file.rb', line 37

def behavior
  @behavior
end

#flagObject (readonly)

Returns the value of attribute flag.



37
38
39
# File 'lib/thor/actions/inject_into_file.rb', line 37

def flag
  @flag
end

#replacementObject (readonly)

Returns the value of attribute replacement.



37
38
39
# File 'lib/thor/actions/inject_into_file.rb', line 37

def replacement
  @replacement
end

Instance Method Details

#invoke!Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/thor/actions/inject_into_file.rb', line 52

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

  if exists?
    if replace!(/#{flag}/, content, config[:force])
      say_status(:invoke)
    elsif replacement_present?
      say_status(:unchanged, color: :blue)
    else
      say_status(:unchanged, warning: WARNINGS[:unchanged_no_flag], color: :red)
    end
  else
    unless pretend?
      raise Thor::Error, "The file #{ destination } does not appear to exist"
    end
  end
end

#revoke!Object



74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/thor/actions/inject_into_file.rb', line 74

def revoke!
  say_status :revoke

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

  replace!(regexp, content, true)
end