Class: CSD::Commands::Replacer
Overview
This class is yielded by the replace function in a block
Class Attribute Summary collapse
-
.filepath ⇒ Object
Returns the value of attribute filepath.
Class Method Summary collapse
-
.replace(pattern, substitution, params = {}) ⇒ Object
Replaces all occurences of a pattern in a file.
Class Attribute Details
.filepath ⇒ Object
Returns the value of attribute filepath.
165 166 167 |
# File 'lib/csd/commands.rb', line 165 def filepath @filepath end |
Class Method Details
.replace(pattern, substitution, params = {}) ⇒ Object
Replaces all occurences of a pattern in a file
Returns
This method returns a CommandResult object with the following values:
success?-
trueif the replacement was successful,nilif 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.}" params[:die_on_failure] ? raise(CSD::Error::Command::ReplaceFailed, result.reason) : UI.error(result.reason) end result end |