Class: LinkHum

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

Constant Summary collapse

NOOP =
->(*){}
RESERVED_NAMES =
[:text, :url, :special]
PROTOCOLS =
'(?:https?|ftp)'
URL_PATTERN =
%r{(#{PROTOCOLS}://\p{^Space}+)}i
MAX_DISPLAY_LENGTH =
64

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text) ⇒ LinkHum

Returns a new instance of LinkHum.



39
40
41
# File 'lib/linkhum.rb', line 39

def initialize(text)
  @text = text
end

Class Method Details

.parse(text) ⇒ Object



14
15
16
# File 'lib/linkhum.rb', line 14

def parse(text)
  new(text).parse
end

.special(pattern, name = nil, &block) ⇒ Object



24
25
26
27
28
29
30
31
# File 'lib/linkhum.rb', line 24

def special(pattern, name = nil, &block)
  name ||= "special_#{specials.count + 1}".to_sym

  RESERVED_NAMES.include?(name) and fail(ArgumentError, "#{name} is reserved")
  specials.key?(name) and fail(ArgumentError, "#{name} is already defined")
  
  specials[name] = [pattern, block]
end

.specialsObject



18
19
20
# File 'lib/linkhum.rb', line 18

def specials
  @specials ||= {}
end

.urlify(text, options = {}, &block) ⇒ Object



10
11
12
# File 'lib/linkhum.rb', line 10

def urlify(text, options = {}, &block)
  new(text).urlify(options.merge(link_processor: block))
end

Instance Method Details

#parseObject



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/linkhum.rb', line 43

def parse
  (@text.split(URL_PATTERN) + ['']).tap{|components|
    (components).each_cons(2){|left, right|
      # ['http://google.com', '/ and stuff'] => ['http://google.com/', ' and stuff']
      shift_punct(left, right) if url?(left) && !url?(right)
    }
  }.reject(&:empty?).
  map{|str|
    url?(str) ? {type: :url, content: str} : parse_specials(str)
  }.flatten
end

#urlify(options = {}) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/linkhum.rb', line 55

def urlify(options = {})
  parse.map{|component|
    case component[:type]
    when :url
      process_url(component[:content], options)
    when :text
      process_text(component[:content])
    else
      process_special(component)
    end
  }.join
end