module Anchored::Linker
Constants
- AUTO_LINK_CRE
regexps for determining context, used high-volume
- AUTO_LINK_RE
- BRACKETS
- PUNCTUATION_RE
Public Instance Methods
auto_link(text, options = {}, &block)
click to toggle source
# File lib/anchored/linker.rb, line 7 def auto_link(text, options = {}, &block) return "" if text.to_s.empty? auto_link_urls(text, options, &block) end
remove_target_if_local(href, domain, options)
click to toggle source
remove_target_if_local
(“same.com/x”, “same.com”, target: “_blank”)
> <a href=“http://same.com/xsame.com/x”>http://same.com/x>¶ ↑
remove_target_if_local
(“same.com/x”, “different.com”, target: “_blank”)
> <a href=“same.com/x” target=“_blank”>same.com/x>¶ ↑
modifies options in place
# File lib/anchored/linker.rb, line 19 def remove_target_if_local(href, domain, options) return unless options[:target] options.delete(:target) if href.include?("//#{domain}") end
Private Instance Methods
anchor_attrs(options)
click to toggle source
# File lib/anchored/linker.rb, line 76 def anchor_attrs(options) options.map { |k, v| %(#{k}="#{v}") }.unshift("").join(" ") end
anchor_tag(href, text, options)
click to toggle source
# File lib/anchored/linker.rb, line 80 def anchor_tag(href, text, options) options = options.dup if (domain = options.delete(:domain)) remove_target_if_local href, domain, options end %(<a href="#{href}"#{anchor_attrs(options)}>#{text}</a>) end
auto_link_urls(text, options = {}) { |href| ... }
click to toggle source
Turns all urls into clickable links. If a block is given, each url is yielded and the result is used as the link text.
# File lib/anchored/linker.rb, line 37 def auto_link_urls(text, options = {}) # to_str is for SafeBuffer objects (text marked html_safe) text.to_str.gsub(AUTO_LINK_RE) do match = Regexp.last_match href = match[0] scheme = match[1] punctuation = [] if auto_linked?(match) # do not change string; URL is already linked href else # don't include trailing punctuation character as part of the URL while href.sub!(PUNCTUATION_RE, "") punctuation.push Regexp.last_match(0) if (opening = BRACKETS[punctuation.last]) && href.scan(opening).size > href.scan(punctuation.last).size href << punctuation.pop break end end link_text = block_given? ? yield(href) : href href = "http://" + href unless scheme # content_tag(:a, link_text, html.merge(href: href)) + punctuation.reverse.join('') anchor_tag(href, link_text, options) + punctuation.reverse.join end end end
auto_linked?(match)
click to toggle source
Detects already linked context or position in the middle of a tag Note: this changes the current Regexp
# File lib/anchored/linker.rb, line 69 def auto_linked?(match) left = match.pre_match right = match.post_match (left =~ AUTO_LINK_CRE[0] && right =~ AUTO_LINK_CRE[1]) || (left.rindex(AUTO_LINK_CRE[2]) && Regexp.last_match.post_match !~ AUTO_LINK_CRE[3]) end