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.



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

def initialize(params)
  @params = params
end

Instance Attribute Details

#directionObject

Returns the value of attribute direction.



2
3
4
# File 'lib/pups/replace_command.rb', line 2

def direction
  @direction
end

#filenameObject

Returns the value of attribute filename.



2
3
4
# File 'lib/pups/replace_command.rb', line 2

def filename
  @filename
end

#fromObject

Returns the value of attribute from.



2
3
4
# File 'lib/pups/replace_command.rb', line 2

def from
  @from
end

#globalObject

Returns the value of attribute global.



2
3
4
# File 'lib/pups/replace_command.rb', line 2

def global
  @global
end

#textObject

Returns the value of attribute text.



2
3
4
# File 'lib/pups/replace_command.rb', line 2

def text
  @text
end

#toObject

Returns the value of attribute to.



2
3
4
# File 'lib/pups/replace_command.rb', line 2

def to
  @to
end

Class Method Details

.from_hash(hash, params) ⇒ Object



4
5
6
7
8
9
10
11
12
13
# File 'lib/pups/replace_command.rb', line 4

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



15
16
17
18
# File 'lib/pups/replace_command.rb', line 15

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

Instance Method Details

#replaced_textObject



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

def replaced_text
  new_to = to
  if String === to
    new_to = interpolate_params(to)
  end
  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



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

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