Class: LinkHum
- Inherits:
-
Object
- Object
- LinkHum
- 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
- .parse(text) ⇒ Object
- .special(pattern, name = nil, &block) ⇒ Object
- .specials ⇒ Object
- .urlify(text, options = {}, &block) ⇒ Object
Instance Method Summary collapse
-
#initialize(text) ⇒ LinkHum
constructor
A new instance of LinkHum.
- #parse ⇒ Object
- #urlify(options = {}) ⇒ Object
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 |
.specials ⇒ Object
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, = {}, &block) new(text).urlify(.merge(link_processor: block)) end |
Instance Method Details
#parse ⇒ Object
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( = {}) parse.map{|component| case component[:type] when :url process_url(component[:content], ) when :text process_text(component[:content]) else process_special(component) end }.join end |