Class: Pups::ReplaceCommand

Inherits:
Command
  • Object
show all
Defined in:
lib/pups/replace_command.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Command

#interpolate_params, interpolate_params, run

Constructor Details

#initialize(params) ⇒ ReplaceCommand

Returns a new instance of ReplaceCommand.



23
24
25
# File 'lib/pups/replace_command.rb', line 23

def initialize(params)
  @params = params
end

Instance Attribute Details

#directionObject

Returns the value of attribute direction.



5
6
7
# File 'lib/pups/replace_command.rb', line 5

def direction
  @direction
end

#filenameObject

Returns the value of attribute filename.



5
6
7
# File 'lib/pups/replace_command.rb', line 5

def filename
  @filename
end

#fromObject

Returns the value of attribute from.



5
6
7
# File 'lib/pups/replace_command.rb', line 5

def from
  @from
end

#globalObject

Returns the value of attribute global.



5
6
7
# File 'lib/pups/replace_command.rb', line 5

def global
  @global
end

#textObject

Returns the value of attribute text.



5
6
7
# File 'lib/pups/replace_command.rb', line 5

def text
  @text
end

#toObject

Returns the value of attribute to.



5
6
7
# File 'lib/pups/replace_command.rb', line 5

def to
  @to
end

Class Method Details

.from_hash(hash, params) ⇒ Object



7
8
9
10
11
12
13
14
15
16
# File 'lib/pups/replace_command.rb', line 7

def self.from_hash(hash, params)
  replacer = new(params)
  replacer.from = guess_replace_type(hash["from"])
  replacer.to = guess_replace_type(hash["to"])
  replacer.text = File.read(hash["filename"])
  replacer.filename = hash["filename"]
  replacer.direction = hash["direction"].to_sym if hash["direction"]
  replacer.global = hash["global"].to_s == "true"
  replacer
end

.guess_replace_type(item) ⇒ Object



18
19
20
21
# File 'lib/pups/replace_command.rb', line 18

def self.guess_replace_type(item)
  # evaling to get all the regex flags easily
  item[0] == "/" ? eval(item) : item # rubocop:disable Security/Eval
end

Instance Method Details

#replaced_textObject



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/pups/replace_command.rb', line 27

def replaced_text
  new_to = to
  new_to = interpolate_params(to) if to.is_a?(String)
  if global
    text.gsub(from, new_to)
  elsif direction == :reverse
    index = text.rindex(from)
    text[0..index - 1] << text[index..-1].sub(from, new_to)
  else
    text.sub(from, new_to)
  end
end

#runObject



40
41
42
43
# File 'lib/pups/replace_command.rb', line 40

def run
  Pups.log.info("Replacing #{from} with #{to} in #{filename}")
  File.open(filename, "w") { |f| f.write replaced_text }
end