Class: Pry::Hackage::Hack

Inherits:
Object
  • Object
show all
Defined in:
lib/pry/hack.rb

Overview

The base class from which all Hacks extend

Direct Known Subclasses

ModOpHack

Instance Method Summary collapse

Constructor Details

#initialize(regex, &block) ⇒ Hack

Object initialization.

Parameters:

  • regex (Regexp)

    The regular expression that matches the hack

  • block (Proc)

    The block passed to the method detailing the hack’s action.



79
80
81
82
83
84
85
# File 'lib/pry/hack.rb', line 79

def initialize(regex, &block)
  @PATTERN = regex
  @CODE    = block
  define_singleton_method(:capture) do |x|
    [][x]
  end
end

Instance Method Details

#ignoreObject



132
133
134
# File 'lib/pry/hack.rb', line 132

def ignore
  return nil
end

#replace(text, hash) ⇒ String

DSL function that acts like String#sub

Parameters:

  • text (String)

    The text that will be subject to the sub.

  • hash (Hash, String)

    If a hash, you must use the format :with => “text” and you may also supply :global? => true to apply a global substitution. See String#gsub

Returns:

  • (String)

    The string post operations.



120
121
122
123
124
125
126
127
128
129
130
# File 'lib/pry/hack.rb', line 120

def replace(text, hash)
  if hash.is_a? Hash
    if hash[:global?].nil? || hash[:global?]
      return text.gsub(@PATTERN, hash[:with])
    else
      return text.sub(@PATTERN, hash[:with])
    end
  else
    return text.gsub(@PATTERN, hash)
  end
end

#replace_with(text) ⇒ Object

DSL function that replaces the entire string with the one provided.



107
108
109
# File 'lib/pry/hack.rb', line 107

def replace_with(text)
  return text
end

#run(where) ⇒ Object



102
103
104
# File 'lib/pry/hack.rb', line 102

def run(where)
  instance_exec(nil, where, &@CODE)
end

#score(text) ⇒ Fixnum

Lexical score of a string in relation to the regular expression of the hack.

Parameters:

  • text (String)

    The text to be tested for a numerical matching score.

Returns:

  • (Fixnum)

    The score given, or characters matched by the regular expression.



92
93
94
95
96
97
98
99
100
# File 'lib/pry/hack.rb', line 92

def score(text)
  md = @PATTERN.match(text)
  return if md.nil?
  cap = md.captures
  define_singleton_method(:capture) do |x|
    cap[x-1]
  end
  return cap.join.length
end