Class: Permalink::Normalizer

Inherits:
Object
  • Object
show all
Defined in:
app/models/permalink.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source) ⇒ Normalizer

Returns a new instance of Normalizer.



16
17
18
19
# File 'app/models/permalink.rb', line 16

def initialize(source)
  @source = source
  @rules = source.split("|").map { |rule| parse_rule(rule) }.compact if source.present?
end

Instance Attribute Details

#sourceObject (readonly)

Returns the value of attribute source.



14
15
16
# File 'app/models/permalink.rb', line 14

def source
  @source
end

Instance Method Details

#normalize(url) ⇒ Object



43
44
45
46
47
48
# File 'app/models/permalink.rb', line 43

def normalize(url)
  return url unless @rules
  @rules.each { |(regex, sub)| url = url.sub(regex, sub) }

  url
end

#parse_rule(rule) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'app/models/permalink.rb', line 21

def parse_rule(rule)
  return unless rule =~ %r{/.*/}

  escaping = false
  regex = +""
  sub = +""
  c = 0

  rule.chars.each do |l|
    c += 1 if !escaping && l == "/"
    escaping = l == "\\"

    if c > 1
      sub << l
    else
      regex << l
    end
  end

  [Regexp.new(regex[1..-1]), sub[1..-1] || ""] if regex.length > 1
end