Module: Twitter::Rewriter

Extended by:
Deprecation, Rewriter
Included in:
Rewriter
Defined in:
lib/twitter-text/rewriter.rb

Overview

A module provides base methods to rewrite usernames, lists, hashtags and URLs.

Instance Method Summary collapse

Methods included from Deprecation

deprecate

Instance Method Details

#rewrite(text, options = {}) ⇒ Object



28
29
30
31
32
# File 'lib/twitter-text/rewriter.rb', line 28

def rewrite(text, options = {})
  [:hashtags, :urls, :usernames_or_lists].inject(text) do |key|
    options[key] ? send(:"rewrite_#{key}", text, &options[key]) : text
  end
end

#rewrite_entities(text, entities) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/twitter-text/rewriter.rb', line 4

def rewrite_entities(text, entities)
  chars = text.to_s.to_char_a

  # sort by start index
  entities = entities.sort_by do |entity|
    indices = entity.respond_to?(:indices) ? entity.indices : entity[:indices]
    indices.first
  end

  result = []
  last_index = entities.inject(0) do |index, entity|
    indices = entity.respond_to?(:indices) ? entity.indices : entity[:indices]
    result << chars[index...indices.first]
    result << yield(entity, chars)
    indices.last
  end
  result << chars[last_index..-1]

  result.flatten.join
end

#rewrite_hashtags(text) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/twitter-text/rewriter.rb', line 46

def rewrite_hashtags(text)
  entities = Extractor.extract_hashtags_with_indices(text)
  rewrite_entities(text, entities) do |entity, chars|
    hash = chars[entity[:indices].first]
    yield(hash, entity[:hashtag])
  end
end

#rewrite_urls(text) ⇒ Object



55
56
57
58
59
60
# File 'lib/twitter-text/rewriter.rb', line 55

def rewrite_urls(text)
  entities = Extractor.extract_urls_with_indices(text, :extract_url_without_protocol => false)
  rewrite_entities(text, entities) do |entity, chars|
    yield(entity[:url])
  end
end

#rewrite_usernames_or_lists(text) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/twitter-text/rewriter.rb', line 35

def rewrite_usernames_or_lists(text)
  entities = Extractor.extract_mentions_or_lists_with_indices(text)
  rewrite_entities(text, entities) do |entity, chars|
    at = chars[entity[:indices].first]
    list_slug = entity[:list_slug]
    list_slug = nil if list_slug.empty?
    yield(at, entity[:screen_name], list_slug)
  end
end