Method: PatternPatch::Patch#apply

Defined in:
lib/pattern_patch/patch.rb

#apply(files, options = {}) ⇒ Object

Applies the patch to one or more files. ERB is processed in the text field, whether it comes from a text_file or not. Pass a Binding to ERB using the :binding option or a Hash of locals. Pass the :offset option to specify a starting offset, in characters, from the beginning of the file.

Parameters:

  • files (Array, String)

    One or more file paths to which to apply the patch.

  • options (Hash) (defaults to: {})

    Options for applying the patch.

Options Hash (options):

  • :binding (Binding) — default: nil

    A Binding object to use when rendering ERB

  • :offset (Integer) — default: 0

    Offset in characters

  • :safe_level (Object, nil) — default: PatternPatch.safe_level

    A valid value for $SAFE for use with ERb

  • :trim_mode (String) — default: PatternPatch.trim_mode

    A valid ERb trim mode

  • :locals (Hash)

    A Hash of local variables for rendering the template

Raises:

  • (ArgumentError)

    In case of invalid mode (other than :append, :prepend, :replace)



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/pattern_patch/patch.rb', line 131

def apply(files, options = {})
  offset = options[:offset] || 0
  files = [files] if files.kind_of? String

  safe_level = options[:safe_level] || PatternPatch.safe_level
  trim_mode = options[:trim_mode] || PatternPatch.trim_mode

  locals = options[:locals]

  raise ArgumentError, ':binding is incompatible with :locals' if options[:binding] && locals

  renderer = Renderer.new text, safe_level, trim_mode
  if locals.nil?
    patch_text = renderer.render options[:binding]
  else
    patch_text = renderer.render locals
  end

  files.each do |path|
    modified = Utilities.apply_patch File.read(path),
                                     regexp,
                                     patch_text,
                                     global,
                                     mode,
                                     offset
    File.write path, modified
  end
end