Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/lydown/core_ext.rb

Constant Summary collapse

UNESCAPES =

String unescaping code from here: stackoverflow.com/a/20131717

{
    'a' => "\x07", 'b' => "\x08", 't' => "\x09",
    'n' => "\x0a", 'v' => "\x0b", 'f' => "\x0c",
    'r' => "\x0d", 'e' => "\x1b", "\\\\" => "\x5c",
    "\"" => "\x22", "'" => "\x27"
}

Instance Method Summary collapse

Instance Method Details

#calculate_line_indexesObject



143
144
145
146
147
148
149
150
151
152
# File 'lib/lydown/core_ext.rb', line 143

def calculate_line_indexes
  i = -1
  indexes = {0 => 0}
  line = 1
  while i = index("\n", i + 1)
    indexes[line] = i + 1 # first character after line break
    line += 1
  end
  indexes
end

#camelizeObject



117
118
119
# File 'lib/lydown/core_ext.rb', line 117

def camelize
  split('_').collect(&:capitalize).join
end

#find_line_and_column(index) ⇒ Object



154
155
156
157
158
159
160
161
162
163
164
# File 'lib/lydown/core_ext.rb', line 154

def find_line_and_column(index)
  @line_indexes ||= calculate_line_indexes
  line = @line_indexes.reverse_each {|l, i| break l if i <= index}
  
  # return line and column
  if line.nil?
    [nil, nil]
  else
    [(line + 1), (index - @line_indexes[line] + 1)]
  end
end

#titlize(all_capitals = false) ⇒ Object



111
112
113
114
115
# File 'lib/lydown/core_ext.rb', line 111

def titlize(all_capitals = false)
  all_capitals ? 
    self.gsub("-", " ").gsub(/\b('?[a-z])/) {$1.capitalize} :
    self.gsub("-", " ").capitalize
end

#unescapeObject



130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/lydown/core_ext.rb', line 130

def unescape
  # Escape all the things
  gsub(/\\(?:([#{UNESCAPES.keys.join}])|u([\da-fA-F]{4}))|\\0?x([\da-fA-F]{2})/) {
    if $1
      if $1 == '\\' then '\\' else UNESCAPES[$1] end
    elsif $2 # escape \u0000 unicode
      ["#$2".hex].pack('U*')
    elsif $3 # escape \0xff or \xff
      [$3].pack('H2')
    end
  }
end

#uri_escapeObject



166
167
168
# File 'lib/lydown/core_ext.rb', line 166

def uri_escape
  EscapeUtils.escape_uri(self)
end