Module: Herbert::Ajaxify

Defined in:
lib/herbert/Ajaxify.rb

Overview

Enhances AJAJ/AJAX support

Constant Summary collapse

Headers =

Headers to send with each request

{
  'Access-Control-Allow-Methods' => %w{POST GET PUT DELETE OPTIONS},
  'Access-Control-Allow-Headers' => %w{Content-Type X-Requested-With},
  'Access-Control-Allow-Origin' => %w{*},
  'Access-Control-Expose-Header' => %w{Content-Type Content-Length X-Build},
  'X-Build' => [Herbert::Utils.version]
}

Class Method Summary collapse

Class Method Details

.registered(app) ⇒ Object

  • Loads config/headers.rb

  • Enables header processing

  • Registers CORS proxy for external services

Parameters:



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/herbert/Ajaxify.rb', line 23

def self.registered(app)
  # Heeeaderzz!!! Gimme heaaaderzzz!!!
  path = File.join(app.settings.root, 'config','headers.rb')
  if File.exists?(path) then
    log.h_debug("Loading additional headers from #{path}")
    custom = eval(File.open(path).read)
    custom.each {|name, value|
      value = [value] unless value.is_a?(Array)
      Headers[name] = (Headers[name] || []) | value
    }
  else
    log.h_info("File #{path} doesn't exists; no additional headers loaded")
  end

  app.before do
# Add the headers to the response
    Headers.each {|name, value|
      value = [value] unless value.is_a?(Array)
      value.map! {|val|
        (val.is_a?(Proc) ? val.call : val).to_s
      }
      response[name] = value.join(', ')
    }
  end
  
  # enable OPTIONS verb
  class << Sinatra::Base
    def http_options path, opts={}, &block
      route 'OPTIONS', path, opts, &block
    end
  end
  Sinatra::Delegator.delegate :http_options
  
  # Proxy for not CORS enabled services such as 
  # Google Maps
  # /proxy/url?=
  app.get '/proxy/' do
    url = URI.parse(URI.encode(params[:url]))
    res = Net::HTTP.start(url.host, 80) {|http|
      http.get(url.path + '?' + url.query)
    }
    response['content-type'] = res['content-type']
    res.body
  end
end