Class: Publicious

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

Constant Summary collapse

FILE_METHODS =
%w(GET HEAD).freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Publicious

Returns a new instance of Publicious.



9
10
11
12
# File 'lib/publicious.rb', line 9

def initialize(app)
  @app = app
  yield if block_given?
end

Class Method Details

.add_engines_public_paths!Object



68
69
70
71
72
# File 'lib/publicious.rb', line 68

def self.add_engines_public_paths!
  ::Rails::Engine.subclasses.map { |klass|
    klass.config.paths.public.paths.first
  }.flatten.compact.reject { |path| path =~ /publicious/}
end

.allowed_dirsObject



56
57
58
# File 'lib/publicious.rb', line 56

def self.allowed_dirs
  %w(stylesheets javascripts images)
end

.public_pathsObject



60
61
62
63
64
65
66
# File 'lib/publicious.rb', line 60

def self.public_paths
  @public_paths ||= begin
    paths = []
    paths += add_engines_public_paths! if defined?(::Rails::Engine)
    paths
  end
end

Instance Method Details

#call(env) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/publicious.rb', line 18

def call(env)
  puts "we're in Publicious"
  request = Rack::Request.new(env)
  return @app.call(env) unless FILE_METHODS.include?(request.request_method)

  if request.path_info =~  %r{^\/(#{klass.allowed_dirs.join("|")})}
    file_name = nil
    path = nil

    klass.public_paths.detect do |pub_path|
      path = pub_path
      fp   = File.join(pub_path, request.path_info)
      file_name = fp if File.file?(fp)
    end

    return respond_not_found! unless file_name

    # Make sure pricks aren't ../../config/database.yml ing us
    respond_not_found! unless file_name.gsub(%r[^#{path}], "") == request.path_info

    Rack::Response.new(
      File.open(file_name),
      200,'Content-Type' => content_type_for_file(file_name)
    ).finish
  else
    @app.call(env)
  end
end

#content_type_for_file(name) ⇒ Object



51
52
53
54
# File 'lib/publicious.rb', line 51

def content_type_for_file(name)
  file_name = File.basename(name).split(".").last.to_s
  Mime::Type.lookup_by_extension(file_name).to_s
end

#klassObject



14
15
16
# File 'lib/publicious.rb', line 14

def klass
  self.class
end

#respond_not_found!Object



47
48
49
# File 'lib/publicious.rb', line 47

def respond_not_found!
  Rack::Response.new("Not Found", 404).finish
end