Class: Kiosk::Rewriter

Inherits:
Object
  • Object
show all
Defined in:
lib/kiosk/rewriter.rb

Overview

Rewrites the content of resources.

Instance Method Summary collapse

Constructor Details

#initializeRewriter

Creates a new content rewriter.



10
11
12
13
# File 'lib/kiosk/rewriter.rb', line 10

def initialize
  @claims = {}
  @rewrites = []
end

Instance Method Details

#add_claim(claim, options = {}) ⇒ Object

Adds a Claim to the rewriter. This is typically done indirectly using Resource.claims_content in each resource model.

Options:

  • :priority: Claims with higher priority (a lower value) take

    precedence. Symbols +:high+, +:normal+, +:low+ map to
    values -9, 0, and 9 respectively.
    


24
25
26
27
28
29
30
31
32
# File 'lib/kiosk/rewriter.rb', line 24

def add_claim(claim, options = {})
  priority = {
    :high => -9,
    :normal => 0,
    :low => 9
  }.fetch(options[:priority], options[:priority] || 0)

  (@claims[priority] || (@claims[priority] = [])) << claim
end

#add_rewrite(rewrite) ⇒ Object

Adds a rewrite rule to the rewriter. This is typically done indirectly using Controller.rewrite_content_for in each controller.



37
38
39
# File 'lib/kiosk/rewriter.rb', line 37

def add_rewrite(rewrite)
  @rewrites << rewrite
end

#reset!Object

Clears all rewrite rules.



43
44
45
# File 'lib/kiosk/rewriter.rb', line 43

def reset!
  @rewrites.clear
end

#rewrite(content) ⇒ Object

Returns the rewriten document from rewrite_to_document as a string.



49
50
51
# File 'lib/kiosk/rewriter.rb', line 49

def rewrite(content)
  rewrite_to_document(content).to_html
end

#rewrite_to_document(content) ⇒ Object

Runs on claims on the given content, incorporates all controller rewrites, and returns the resulting content.



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/kiosk/rewriter.rb', line 56

def rewrite_to_document(content)
  document = Document.parse(content)

  # Claims are grouped by priority. Process them in order.
  @claims.keys.sort.each do |k|

    # Iterate of all claims in this priority group.
    @claims[k].each do |claim|

      # Stake the claim on the content.
      claim.stake!(document) do |node|
        # Process all rewrites on the claimed node.
        @rewrites.each do |rewrite|
          rewrite.evaluate(node) if rewrite.matches?(node)
        end
      end
    end
  end

  document
end