Class: Rack::Combobot

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/combobot.rb,
lib/rack/combobot/config.rb,
lib/rack/combobot/combination.rb

Defined Under Namespace

Classes: Combination, Config

Constant Summary collapse

MIME_TYPES =
{
  "js"  => "text/javascript",
  "css" => "text/css"
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Combobot

Returns a new instance of Combobot.



18
19
20
21
22
23
# File 'lib/rack/combobot.rb', line 18

def initialize(app, options = {})
  @app = app

  options[:root] = Pathname.new(options[:root] || Dir.pwd)
  @config = Rack::Combobot::Config.new(options)
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



11
12
13
# File 'lib/rack/combobot.rb', line 11

def config
  @config
end

Instance Method Details

#call(env) ⇒ Object

rack request handler



26
27
28
29
30
31
32
33
34
# File 'lib/rack/combobot.rb', line 26

def call(env)
  request = Rack::Request.new(env)

  if request.path =~ /^\/combobot/
    combine(request)
  else
    @app.call(env)
  end
end

#combine(request) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/rack/combobot.rb', line 36

def combine(request)
  file_names = extract_file_names_from_request(request)

  return not_found if file_names.empty?

  extension = file_names[0].split(".").last
  headers   = create_headers(extension)

  begin
    combo = Combination.new(@config.root, file_names).combine
    [200, headers, [combo]]
  rescue Combination::PathError
    not_found
  end
end

#create_headers(extension) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/rack/combobot.rb', line 66

def create_headers(extension)
  headers = {"Content-Type" => MIME_TYPES[extension]}

  if @config.expires
    headers['Expires'] = @config.expires.httpdate
  end
  
  if @config.cache_control
    headers['Cache-Control'] = @config.cache_control
  end

  headers
end

#extract_file_names_from_request(request) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/rack/combobot.rb', line 52

def extract_file_names_from_request(request)
  path = request.path
  file_names = request.query_string

  if file_names == '' && path =~ /.js|.css/
    file_names = path.split('&')
    file_names.slice!(0)
  else
    file_names = file_names.split("&")
  end

  file_names
end

#not_foundObject



80
81
82
# File 'lib/rack/combobot.rb', line 80

def not_found
  [404, {'Content-Type' => 'text/html'}, ['File not found']]
end