Class: SimpleFormat::AutoLink
- Inherits:
-
Object
- Object
- SimpleFormat::AutoLink
- Defined in:
- lib/simple_format/auto_link.rb
Instance Method Summary collapse
- #all(text) ⇒ Object
-
#email_addresses(text) ⇒ Object
Turns all email addresses into clickable links.
-
#initialize ⇒ AutoLink
constructor
A new instance of AutoLink.
-
#urls(text) ⇒ Object
Turns all urls into clickable links.
Constructor Details
#initialize ⇒ AutoLink
Returns a new instance of AutoLink.
6 7 8 9 10 11 12 13 14 |
# File 'lib/simple_format/auto_link.rb', line 6 def initialize() @regex = { protocol: %r{(?: ((?:ed2k|ftp|http|https|irc|mailto|news|gopher|nntp|telnet|webcal|xmpp|callto|feed|svn|urn|aim|rsync|tag|ssh|sftp|rtsp|afs|file):)// | www\. )[^\s<]+}x, href: [/<[^>]+$/, /^[^>]*>/, /<a\b.*?>/i, /<\/a>/i], mail: /[\w.!#\$%+-]+@[\w-]+(?:\.[\w-]+)+/, brackets: { ']' => '[', ')' => '(', '}' => '{' }, word_pattern: RUBY_VERSION < '1.9' ? '\w' : '\p{Word}' } end |
Instance Method Details
#all(text) ⇒ Object
16 17 18 19 |
# File 'lib/simple_format/auto_link.rb', line 16 def all(text) return text unless text email_addresses( urls(text) ) end |
#email_addresses(text) ⇒ Object
Turns all email addresses into clickable links. If a block is given, each email is yielded and the result is used as the link text.
52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/simple_format/auto_link.rb', line 52 def email_addresses(text) text.gsub(@regex[:mail]) do text = $& if auto_linked?($`, $') text else display_text = (block_given?) ? yield(text) : text # mail_to text, display_text "<a href='mailto:#{text}'>#{display_text}</a>" end end end |
#urls(text) ⇒ Object
Turns all urls into clickable links. If a block is given, each url is yielded and the result is used as the link text.
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/simple_format/auto_link.rb', line 23 def urls(text) text.gsub(@regex[:protocol]) do scheme, href = $1, $& punctuation = [] if auto_linked?($`, $') # do not change string; URL is already linked href else # don't include trailing punctuation character as part of the URL while href.sub!(/[^#{@regex[:word_pattern]}\/-]$/, '') punctuation.push $& if opening = @regex[:brackets][punctuation.last] and href.scan(opening).size > href.scan(punctuation.last).size href << punctuation.pop break end end link_text = block_given?? yield(href) : href href = '//' + href unless scheme "<a href='#{href}' target='_blank'>#{link_text}</a>" + punctuation.reverse.join('') end end end |