Class: CSD::Commands::Replacer

Inherits:
Object
  • Object
show all
Defined in:
lib/csd/commands.rb

Overview

This class is yielded by the replace function in a block

Class Attribute Summary (collapse)

Class Method Summary (collapse)

Class Attribute Details

+ (Object) filepath

Returns the value of attribute filepath



165
166
167
# File 'lib/csd/commands.rb', line 165

def filepath
  @filepath
end

Class Method Details

+ (Object) replace(pattern, substitution, params = {})

Replaces all occurences of a pattern in a file

Returns

This method returns a CommandResult object with the following values:

success?

true if the replacement was successful, nil if not.



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/csd/commands.rb', line 176

def self.replace(pattern, substitution, params={})
  result = CommandResult.new
  default_params = { :die_on_failure => true, :only_first_occurence => false }
  params = default_params.merge(params)
  begin
    new_file_content = if params[:only_first_occurence]
      UI.info "   Replacing the first occurence of".yellow
      File.read(self.filepath).sub(pattern, substitution) unless Options.reveal
    else
      UI.info "   Replacing".yellow
      File.read(self.filepath).gsub(pattern, substitution) unless Options.reveal
    end
    UI.info "   `#{pattern}´".blue
    UI.info "   with".yellow
    UI.info "   `#{substitution.to_s.gsub("\n", "\n    ")}´".white
    File.open(self.filepath, 'w+') { |file| file << new_file_content } unless Options.reveal
    result.success = true
  rescue Errno::ENOENT => e
    if Options.reveal
      result.success = true
      return result
    end
    result.success = false
    result.reason = "Could not perform replace operation! #{e.message}"
    params[:die_on_failure] ? raise(CSD::Error::Command::ReplaceFailed, result.reason) : UI.error(result.reason)
  end
  result
end