Class: ReeText::Excerpt

Inherits:
Object
  • Object
show all
Includes:
Ree::FnDSL
Defined in:
lib/ree_lib/packages/ree_text/package/ree_text/functions/excerpt.rb

Constant Summary collapse

DEFAULTS =
{
  radius: 100,
  omission: "...",
  separator: ""
}

Instance Method Summary collapse

Instance Method Details

#call(text, phrase, **opts) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/ree_lib/packages/ree_text/package/ree_text/functions/excerpt.rb', line 52

def call(text, phrase, **opts)
  options = DEFAULTS.merge(opts)
  
  return if is_blank(text) && is_blank(phrase)

  separator = options[:separator]

  case phrase
  when Regexp
    regex = phrase
  else
    regex = /#{Regexp.escape(phrase)}/i
  end

  return unless matches = text.match(regex)
  phrase = matches[0]

  unless is_blank(separator)
    text.split(separator).each do |value|
      if value.match?(regex)
        phrase = value
        break
      end
    end
  end

  first_part, second_part = text.split(phrase, 2)

  prefix, first_part   = cut_excerpt_part(:first, first_part, separator, options)
  postfix, second_part = cut_excerpt_part(:second, second_part, separator, options)

  affix = [first_part, separator, phrase, separator, second_part].join.strip
  [prefix, affix, postfix].join
end