Class: Freyia::Automations::InjectIntoFile

Inherits:
EmptyDirectory show all
Defined in:
lib/freyia/automations/inject_into_file.rb

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.



68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/freyia/automations/inject_into_file.rb', line 68

def initialize(base, destination, data, **config)
  super(base, destination, verbose: true, **config)

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

  @replacement = data.is_a?(Proc) ? data.() : data
  @flag = Regexp.escape(@flag) unless @flag.is_a?(Regexp)
  @error_on_no_change = @config.fetch(:error_on_no_change, false)
end

Instance Attribute Details

#behaviorObject (readonly)

Returns the value of attribute behavior.



66
67
68
# File 'lib/freyia/automations/inject_into_file.rb', line 66

def behavior
  @behavior
end

#flagObject (readonly)

Returns the value of attribute flag.



66
67
68
# File 'lib/freyia/automations/inject_into_file.rb', line 66

def flag
  @flag
end

#replacementObject (readonly)

Returns the value of attribute replacement.



66
67
68
# File 'lib/freyia/automations/inject_into_file.rb', line 66

def replacement
  @replacement
end

Instance Method Details

#callObject

rubocop:todo Metrics



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/freyia/automations/inject_into_file.rb', line 82

def call # rubocop:todo Metrics
  content = if @behavior == :after
              "\\0#{replacement}"
            else
              "#{replacement}\\0"
            end

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