File: piwik.rb

package info (click to toggle)
ruby-rack-piwik 0.2.2-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 116 kB
  • ctags: 22
  • sloc: ruby: 108; makefile: 7
file content (35 lines) | stat: -rw-r--r-- 1,067 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
require 'rack'
require 'erb'

module Rack

  class Piwik
    DEFAULT = {} 

    def initialize(app, options = {})
      raise ArgumentError, "piwik_url must be present" unless options[:piwik_url] and !options[:piwik_url].empty?
      raise ArgumentError, "piwik_id must be present" unless options[:piwik_id] and !options[:piwik_id].to_s.empty?
      @app, @options = app, DEFAULT.merge(options)
    end

    def call(env); dup._call(env); end

    def _call(env)
      @status, @headers, @response = @app.call(env)
      return [@status, @headers, @response] unless html?
      response = Rack::Response.new([], @status, @headers)
      @response.each { |fragment| response.write inject(fragment) }
      response.finish
    end

    private

    def html?; @headers['Content-Type'] =~ /html/; end

    def inject(response)
      file = 'async'
      @template ||= ::ERB.new ::File.read ::File.expand_path("../../../../../share/ruby-rack-piwik/templates/#{file}.erb",__FILE__)
      response.gsub(%r{</body>}, @template.result(binding) + "</body>")
    end
  end
end