-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathbase.rb
2167 lines (1802 loc) · 66.7 KB
/
base.rb
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
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# frozen_string_literal: true
# external dependencies
require 'rack'
begin
require 'rackup'
rescue LoadError
end
require 'tilt'
require 'rack/protection'
require 'rack/session'
require 'mustermann'
require 'mustermann/sinatra'
require 'mustermann/regular'
# stdlib dependencies
require 'ipaddr'
require 'time'
require 'uri'
# other files we need
require 'sinatra/indifferent_hash'
require 'sinatra/show_exceptions'
require 'sinatra/version'
require_relative 'middleware/logger'
module Sinatra
# The request object. See Rack::Request for more info:
# https://rubydoc.info/github/rack/rack/main/Rack/Request
class Request < Rack::Request
HEADER_PARAM = /\s*[\w.]+=(?:[\w.]+|"(?:[^"\\]|\\.)*")?\s*/.freeze
HEADER_VALUE_WITH_PARAMS = %r{(?:(?:\w+|\*)/(?:\w+(?:\.|-|\+)?|\*)*)\s*(?:;#{HEADER_PARAM})*}.freeze
# Returns an array of acceptable media types for the response
def accept
@env['sinatra.accept'] ||= if @env.include?('HTTP_ACCEPT') && (@env['HTTP_ACCEPT'].to_s != '')
@env['HTTP_ACCEPT']
.to_s
.scan(HEADER_VALUE_WITH_PARAMS)
.map! { |e| AcceptEntry.new(e) }
.sort
else
[AcceptEntry.new('*/*')]
end
end
def accept?(type)
preferred_type(type).to_s.include?(type)
end
def preferred_type(*types)
return accept.first if types.empty?
types.flatten!
return types.first if accept.empty?
accept.detect do |accept_header|
type = types.detect { |t| MimeTypeEntry.new(t).accepts?(accept_header) }
return type if type
end
end
alias secure? ssl?
def forwarded?
!forwarded_authority.nil?
end
def safe?
get? || head? || options? || trace?
end
def idempotent?
safe? || put? || delete? || link? || unlink?
end
def link?
request_method == 'LINK'
end
def unlink?
request_method == 'UNLINK'
end
def params
super
rescue Rack::Utils::ParameterTypeError, Rack::Utils::InvalidParameterError => e
raise BadRequest, "Invalid query parameters: #{Rack::Utils.escape_html(e.message)}"
rescue EOFError => e
raise BadRequest, "Invalid multipart/form-data: #{Rack::Utils.escape_html(e.message)}"
end
class AcceptEntry
attr_accessor :params
attr_reader :entry
def initialize(entry)
params = entry.scan(HEADER_PARAM).map! do |s|
key, value = s.strip.split('=', 2)
value = value[1..-2].gsub(/\\(.)/, '\1') if value.start_with?('"')
[key, value]
end
@entry = entry
@type = entry[/[^;]+/].delete(' ')
@params = params.to_h
@q = @params.delete('q') { 1.0 }.to_f
end
def <=>(other)
other.priority <=> priority
end
def priority
# We sort in descending order; better matches should be higher.
[@q, -@type.count('*'), @params.size]
end
def to_str
@type
end
def to_s(full = false)
full ? entry : to_str
end
def respond_to?(*args)
super || to_str.respond_to?(*args)
end
def method_missing(*args, &block)
to_str.send(*args, &block)
end
end
class MimeTypeEntry
attr_reader :params
def initialize(entry)
params = entry.scan(HEADER_PARAM).map! do |s|
key, value = s.strip.split('=', 2)
value = value[1..-2].gsub(/\\(.)/, '\1') if value.start_with?('"')
[key, value]
end
@type = entry[/[^;]+/].delete(' ')
@params = params.to_h
end
def accepts?(entry)
File.fnmatch(entry, self) && matches_params?(entry.params)
end
def to_str
@type
end
def matches_params?(params)
return true if @params.empty?
params.all? { |k, v| !@params.key?(k) || @params[k] == v }
end
end
end
# The response object. See Rack::Response and Rack::Response::Helpers for
# more info:
# https://rubydoc.info/github/rack/rack/main/Rack/Response
# https://rubydoc.info/github/rack/rack/main/Rack/Response/Helpers
class Response < Rack::Response
DROP_BODY_RESPONSES = [204, 304].freeze
def body=(value)
value = value.body while Rack::Response === value
@body = String === value ? [value.to_str] : value
end
def each
block_given? ? super : enum_for(:each)
end
def finish
result = body
if drop_content_info?
headers.delete 'content-length'
headers.delete 'content-type'
end
if drop_body?
close
result = []
end
if calculate_content_length?
# if some other code has already set content-length, don't muck with it
# currently, this would be the static file-handler
headers['content-length'] = body.map(&:bytesize).reduce(0, :+).to_s
end
[status, headers, result]
end
private
def calculate_content_length?
headers['content-type'] && !headers['content-length'] && (Array === body)
end
def drop_content_info?
informational? || drop_body?
end
def drop_body?
DROP_BODY_RESPONSES.include?(status)
end
end
# Some Rack handlers implement an extended body object protocol, however,
# some middleware (namely Rack::Lint) will break it by not mirroring the methods in question.
# This middleware will detect an extended body object and will make sure it reaches the
# handler directly. We do this here, so our middleware and middleware set up by the app will
# still be able to run.
class ExtendedRack < Struct.new(:app)
def call(env)
result = app.call(env)
callback = env['async.callback']
return result unless callback && async?(*result)
after_response { callback.call result }
setup_close(env, *result)
throw :async
end
private
def setup_close(env, _status, _headers, body)
return unless body.respond_to?(:close) && env.include?('async.close')
env['async.close'].callback { body.close }
env['async.close'].errback { body.close }
end
def after_response(&block)
raise NotImplementedError, 'only supports EventMachine at the moment' unless defined? EventMachine
EventMachine.next_tick(&block)
end
def async?(status, _headers, body)
return true if status == -1
body.respond_to?(:callback) && body.respond_to?(:errback)
end
end
# Behaves exactly like Rack::CommonLogger with the notable exception that it does nothing,
# if another CommonLogger is already in the middleware chain.
class CommonLogger < Rack::CommonLogger
def call(env)
env['sinatra.commonlogger'] ? @app.call(env) : super
end
superclass.class_eval do
alias_method :call_without_check, :call unless method_defined? :call_without_check
def call(env)
env['sinatra.commonlogger'] = true
call_without_check(env)
end
end
end
class Error < StandardError # :nodoc:
end
class BadRequest < Error # :nodoc:
def http_status; 400 end
end
class NotFound < Error # :nodoc:
def http_status; 404 end
end
# Methods available to routes, before/after filters, and views.
module Helpers
# Set or retrieve the response status code.
def status(value = nil)
response.status = Rack::Utils.status_code(value) if value
response.status
end
# Set or retrieve the response body. When a block is given,
# evaluation is deferred until the body is read with #each.
def body(value = nil, &block)
if block_given?
def block.each; yield(call) end
response.body = block
elsif value
unless request.head? || value.is_a?(Rack::Files::BaseIterator) || value.is_a?(Stream)
headers.delete 'content-length'
end
response.body = value
else
response.body
end
end
# Halt processing and redirect to the URI provided.
def redirect(uri, *args)
# SERVER_PROTOCOL is required in Rack 3, fall back to HTTP_VERSION
# for servers not updated for Rack 3 (like Puma 5)
http_version = env['SERVER_PROTOCOL'] || env['HTTP_VERSION']
if (http_version == 'HTTP/1.1') && (env['REQUEST_METHOD'] != 'GET')
status 303
else
status 302
end
# According to RFC 2616 section 14.30, "the field value consists of a
# single absolute URI"
response['Location'] = uri(uri.to_s, settings.absolute_redirects?, settings.prefixed_redirects?)
halt(*args)
end
# Generates the absolute URI for a given path in the app.
# Takes Rack routers and reverse proxies into account.
def uri(addr = nil, absolute = true, add_script_name = true)
return addr if addr.to_s =~ /\A[a-z][a-z0-9+.\-]*:/i
uri = [host = String.new]
if absolute
host << "http#{'s' if request.secure?}://"
host << if request.forwarded? || (request.port != (request.secure? ? 443 : 80))
request.host_with_port
else
request.host
end
end
uri << request.script_name.to_s if add_script_name
uri << (addr || request.path_info).to_s
File.join uri
end
alias url uri
alias to uri
# Halt processing and return the error status provided.
def error(code, body = nil)
if code.respond_to? :to_str
body = code.to_str
code = 500
end
response.body = body unless body.nil?
halt code
end
# Halt processing and return a 404 Not Found.
def not_found(body = nil)
error 404, body
end
# Set multiple response headers with Hash.
def headers(hash = nil)
response.headers.merge! hash if hash
response.headers
end
# Access the underlying Rack session.
def session
request.session
end
# Access shared logger object.
def logger
request.logger
end
# Look up a media type by file extension in Rack's mime registry.
def mime_type(type)
Base.mime_type(type)
end
# Set the content-type of the response body given a media type or file
# extension.
def content_type(type = nil, params = {})
return response['content-type'] unless type
default = params.delete :default
mime_type = mime_type(type) || default
raise format('Unknown media type: %p', type) if mime_type.nil?
mime_type = mime_type.dup
unless params.include?(:charset) || settings.add_charset.all? { |p| !(p === mime_type) }
params[:charset] = params.delete('charset') || settings.default_encoding
end
params.delete :charset if mime_type.include? 'charset'
unless params.empty?
mime_type << (mime_type.include?(';') ? ', ' : ';')
mime_type << params.map do |key, val|
val = val.inspect if val =~ /[";,]/
"#{key}=#{val}"
end.join(', ')
end
response['content-type'] = mime_type
end
# https://html.spec.whatwg.org/#multipart-form-data
MULTIPART_FORM_DATA_REPLACEMENT_TABLE = {
'"' => '%22',
"\r" => '%0D',
"\n" => '%0A'
}.freeze
# Set the Content-Disposition to "attachment" with the specified filename,
# instructing the user agents to prompt to save.
def attachment(filename = nil, disposition = :attachment)
response['Content-Disposition'] = disposition.to_s.dup
return unless filename
params = format('; filename="%s"', File.basename(filename).gsub(/["\r\n]/, MULTIPART_FORM_DATA_REPLACEMENT_TABLE))
response['Content-Disposition'] << params
ext = File.extname(filename)
content_type(ext) unless response['content-type'] || ext.empty?
end
# Use the contents of the file at +path+ as the response body.
def send_file(path, opts = {})
if opts[:type] || !response['content-type']
content_type opts[:type] || File.extname(path), default: 'application/octet-stream'
end
disposition = opts[:disposition]
filename = opts[:filename]
disposition = :attachment if disposition.nil? && filename
filename = path if filename.nil?
attachment(filename, disposition) if disposition
last_modified opts[:last_modified] if opts[:last_modified]
file = Rack::Files.new(File.dirname(settings.app_file))
result = file.serving(request, path)
result[1].each { |k, v| headers[k] ||= v }
headers['content-length'] = result[1]['content-length']
opts[:status] &&= Integer(opts[:status])
halt (opts[:status] || result[0]), result[2]
rescue Errno::ENOENT
not_found
end
# Class of the response body in case you use #stream.
#
# Three things really matter: The front and back block (back being the
# block generating content, front the one sending it to the client) and
# the scheduler, integrating with whatever concurrency feature the Rack
# handler is using.
#
# Scheduler has to respond to defer and schedule.
class Stream
def self.schedule(*) yield end
def self.defer(*) yield end
def initialize(scheduler = self.class, keep_open = false, &back)
@back = back.to_proc
@scheduler = scheduler
@keep_open = keep_open
@callbacks = []
@closed = false
end
def close
return if closed?
@closed = true
@scheduler.schedule { @callbacks.each { |c| c.call } }
end
def each(&front)
@front = front
@scheduler.defer do
begin
@back.call(self)
rescue Exception => e
@scheduler.schedule { raise e }
ensure
close unless @keep_open
end
end
end
def <<(data)
@scheduler.schedule { @front.call(data.to_s) }
self
end
def callback(&block)
return yield if closed?
@callbacks << block
end
alias errback callback
def closed?
@closed
end
end
# Allows to start sending data to the client even though later parts of
# the response body have not yet been generated.
#
# The close parameter specifies whether Stream#close should be called
# after the block has been executed.
def stream(keep_open = false)
scheduler = env['async.callback'] ? EventMachine : Stream
current = @params.dup
stream = if scheduler == Stream && keep_open
Stream.new(scheduler, false) do |out|
until out.closed?
with_params(current) { yield(out) }
end
end
else
Stream.new(scheduler, keep_open) { |out| with_params(current) { yield(out) } }
end
body stream
end
# Specify response freshness policy for HTTP caches (Cache-Control header).
# Any number of non-value directives (:public, :private, :no_cache,
# :no_store, :must_revalidate, :proxy_revalidate) may be passed along with
# a Hash of value directives (:max_age, :s_maxage).
#
# cache_control :public, :must_revalidate, :max_age => 60
# => Cache-Control: public, must-revalidate, max-age=60
#
# See RFC 2616 / 14.9 for more on standard cache control directives:
# http://tools.ietf.org/html/rfc2616#section-14.9.1
def cache_control(*values)
if values.last.is_a?(Hash)
hash = values.pop
hash.reject! { |_k, v| v == false }
hash.reject! { |k, v| values << k if v == true }
else
hash = {}
end
values.map! { |value| value.to_s.tr('_', '-') }
hash.each do |key, value|
key = key.to_s.tr('_', '-')
value = value.to_i if %w[max-age s-maxage].include? key
values << "#{key}=#{value}"
end
response['Cache-Control'] = values.join(', ') if values.any?
end
# Set the Expires header and Cache-Control/max-age directive. Amount
# can be an integer number of seconds in the future or a Time object
# indicating when the response should be considered "stale". The remaining
# "values" arguments are passed to the #cache_control helper:
#
# expires 500, :public, :must_revalidate
# => Cache-Control: public, must-revalidate, max-age=500
# => Expires: Mon, 08 Jun 2009 08:50:17 GMT
#
def expires(amount, *values)
values << {} unless values.last.is_a?(Hash)
if amount.is_a? Integer
time = Time.now + amount.to_i
max_age = amount
else
time = time_for amount
max_age = time - Time.now
end
values.last.merge!(max_age: max_age) { |_key, v1, v2| v1 || v2 }
cache_control(*values)
response['Expires'] = time.httpdate
end
# Set the last modified time of the resource (HTTP 'Last-Modified' header)
# and halt if conditional GET matches. The +time+ argument is a Time,
# DateTime, or other object that responds to +to_time+.
#
# When the current request includes an 'If-Modified-Since' header that is
# equal or later than the time specified, execution is immediately halted
# with a '304 Not Modified' response.
def last_modified(time)
return unless time
time = time_for time
response['Last-Modified'] = time.httpdate
return if env['HTTP_IF_NONE_MATCH']
if (status == 200) && env['HTTP_IF_MODIFIED_SINCE']
# compare based on seconds since epoch
since = Time.httpdate(env['HTTP_IF_MODIFIED_SINCE']).to_i
halt 304 if since >= time.to_i
end
if (success? || (status == 412)) && env['HTTP_IF_UNMODIFIED_SINCE']
# compare based on seconds since epoch
since = Time.httpdate(env['HTTP_IF_UNMODIFIED_SINCE']).to_i
halt 412 if since < time.to_i
end
rescue ArgumentError
end
ETAG_KINDS = %i[strong weak].freeze
# Set the response entity tag (HTTP 'ETag' header) and halt if conditional
# GET matches. The +value+ argument is an identifier that uniquely
# identifies the current version of the resource. The +kind+ argument
# indicates whether the etag should be used as a :strong (default) or :weak
# cache validator.
#
# When the current request includes an 'If-None-Match' header with a
# matching etag, execution is immediately halted. If the request method is
# GET or HEAD, a '304 Not Modified' response is sent.
def etag(value, options = {})
# Before touching this code, please double check RFC 2616 14.24 and 14.26.
options = { kind: options } unless Hash === options
kind = options[:kind] || :strong
new_resource = options.fetch(:new_resource) { request.post? }
unless ETAG_KINDS.include?(kind)
raise ArgumentError, ':strong or :weak expected'
end
value = format('"%s"', value)
value = "W/#{value}" if kind == :weak
response['ETag'] = value
return unless success? || status == 304
if etag_matches?(env['HTTP_IF_NONE_MATCH'], new_resource)
halt(request.safe? ? 304 : 412)
end
if env['HTTP_IF_MATCH']
return if etag_matches?(env['HTTP_IF_MATCH'], new_resource)
halt 412
end
nil
end
# Sugar for redirect (example: redirect back)
def back
request.referer
end
# whether or not the status is set to 1xx
def informational?
status.between? 100, 199
end
# whether or not the status is set to 2xx
def success?
status.between? 200, 299
end
# whether or not the status is set to 3xx
def redirect?
status.between? 300, 399
end
# whether or not the status is set to 4xx
def client_error?
status.between? 400, 499
end
# whether or not the status is set to 5xx
def server_error?
status.between? 500, 599
end
# whether or not the status is set to 404
def not_found?
status == 404
end
# whether or not the status is set to 400
def bad_request?
status == 400
end
# Generates a Time object from the given value.
# Used by #expires and #last_modified.
def time_for(value)
if value.is_a? Numeric
Time.at value
elsif value.respond_to? :to_s
Time.parse value.to_s
else
value.to_time
end
rescue ArgumentError => e
raise e
rescue Exception
raise ArgumentError, "unable to convert #{value.inspect} to a Time object"
end
private
# Helper method checking if a ETag value list includes the current ETag.
def etag_matches?(list, new_resource = request.post?)
return !new_resource if list == '*'
list.to_s.split(/\s*,\s*/).include? response['ETag']
end
def with_params(temp_params)
original = @params
@params = temp_params
yield
ensure
@params = original if original
end
end
# Template rendering methods. Each method takes the name of a template
# to render as a Symbol and returns a String with the rendered output,
# as well as an optional hash with additional options.
#
# `template` is either the name or path of the template as symbol
# (Use `:'subdir/myview'` for views in subdirectories), or a string
# that will be rendered.
#
# Possible options are:
# :content_type The content type to use, same arguments as content_type.
# :layout If set to something falsy, no layout is rendered, otherwise
# the specified layout is used (Ignored for `sass`)
# :layout_engine Engine to use for rendering the layout.
# :locals A hash with local variables that should be available
# in the template
# :scope If set, template is evaluate with the binding of the given
# object rather than the application instance.
# :views Views directory to use.
module Templates
module ContentTyped
attr_accessor :content_type
end
def initialize
super
@default_layout = :layout
@preferred_extension = nil
end
def erb(template, options = {}, locals = {}, &block)
render(:erb, template, options, locals, &block)
end
def haml(template, options = {}, locals = {}, &block)
render(:haml, template, options, locals, &block)
end
def sass(template, options = {}, locals = {})
options[:default_content_type] = :css
options[:exclude_outvar] = true
options[:layout] = nil
render :sass, template, options, locals
end
def scss(template, options = {}, locals = {})
options[:default_content_type] = :css
options[:exclude_outvar] = true
options[:layout] = nil
render :scss, template, options, locals
end
def builder(template = nil, options = {}, locals = {}, &block)
options[:default_content_type] = :xml
render_ruby(:builder, template, options, locals, &block)
end
def liquid(template, options = {}, locals = {}, &block)
render(:liquid, template, options, locals, &block)
end
def markdown(template, options = {}, locals = {})
options[:exclude_outvar] = true
render :markdown, template, options, locals
end
def rdoc(template, options = {}, locals = {})
render :rdoc, template, options, locals
end
def asciidoc(template, options = {}, locals = {})
render :asciidoc, template, options, locals
end
def markaby(template = nil, options = {}, locals = {}, &block)
render_ruby(:mab, template, options, locals, &block)
end
def nokogiri(template = nil, options = {}, locals = {}, &block)
options[:default_content_type] = :xml
render_ruby(:nokogiri, template, options, locals, &block)
end
def slim(template, options = {}, locals = {}, &block)
render(:slim, template, options, locals, &block)
end
def yajl(template, options = {}, locals = {})
options[:default_content_type] = :json
render :yajl, template, options, locals
end
def rabl(template, options = {}, locals = {})
Rabl.register!
render :rabl, template, options, locals
end
# Calls the given block for every possible template file in views,
# named name.ext, where ext is registered on engine.
def find_template(views, name, engine)
yield ::File.join(views, "#{name}.#{@preferred_extension}")
Tilt.default_mapping.extensions_for(engine).each do |ext|
yield ::File.join(views, "#{name}.#{ext}") unless ext == @preferred_extension
end
end
private
# logic shared between builder and nokogiri
def render_ruby(engine, template, options = {}, locals = {}, &block)
if template.is_a?(Hash)
options = template
template = nil
end
template = proc { block } if template.nil?
render engine, template, options, locals
end
def render(engine, data, options = {}, locals = {}, &block)
# merge app-level options
engine_options = settings.respond_to?(engine) ? settings.send(engine) : {}
options.merge!(engine_options) { |_key, v1, _v2| v1 }
# extract generic options
locals = options.delete(:locals) || locals || {}
views = options.delete(:views) || settings.views || './views'
layout = options[:layout]
layout = false if layout.nil? && options.include?(:layout)
eat_errors = layout.nil?
layout = engine_options[:layout] if layout.nil? || (layout == true && engine_options[:layout] != false)
layout = @default_layout if layout.nil? || (layout == true)
layout_options = options.delete(:layout_options) || {}
content_type = options.delete(:default_content_type)
content_type = options.delete(:content_type) || content_type
layout_engine = options.delete(:layout_engine) || engine
scope = options.delete(:scope) || self
exclude_outvar = options.delete(:exclude_outvar)
options.delete(:layout)
# set some defaults
options[:outvar] ||= '@_out_buf' unless exclude_outvar
options[:default_encoding] ||= settings.default_encoding
# compile and render template
begin
layout_was = @default_layout
@default_layout = false
template = compile_template(engine, data, options, views)
output = template.render(scope, locals, &block)
ensure
@default_layout = layout_was
end
# render layout
if layout
extra_options = { views: views, layout: false, eat_errors: eat_errors, scope: scope }
options = options.merge(extra_options).merge!(layout_options)
catch(:layout_missing) { return render(layout_engine, layout, options, locals) { output } }
end
if content_type
# sass-embedded returns a frozen string
output = +output
output.extend(ContentTyped).content_type = content_type
end
output
end
def compile_template(engine, data, options, views)
eat_errors = options.delete :eat_errors
template = Tilt[engine]
raise "Template engine not found: #{engine}" if template.nil?
case data
when Symbol
template_cache.fetch engine, data, options, views do
body, path, line = settings.templates[data]
if body
body = body.call if body.respond_to?(:call)
template.new(path, line.to_i, options) { body }
else
found = false
@preferred_extension = engine.to_s
find_template(views, data, template) do |file|
path ||= file # keep the initial path rather than the last one
found = File.exist?(file)
if found
path = file
break
end
end
throw :layout_missing if eat_errors && !found
template.new(path, 1, options)
end
end
when Proc
compile_block_template(template, options, &data)
when String
template_cache.fetch engine, data, options, views do
compile_block_template(template, options) { data }
end
else
raise ArgumentError, "Sorry, don't know how to render #{data.inspect}."
end
end
def compile_block_template(template, options, &body)
first_location = caller_locations.first
path = first_location.path
line = first_location.lineno
path = options[:path] || path
line = options[:line] || line
template.new(path, line.to_i, options, &body)
end
end
# Extremely simple template cache implementation.
# * Not thread-safe.
# * Size is unbounded.
# * Keys are not copied defensively, and should not be modified after
# being passed to #fetch. More specifically, the values returned by
# key#hash and key#eql? should not change.
#
# Implementation copied from Tilt::Cache.
class TemplateCache
def initialize
@cache = {}
end
# Caches a value for key, or returns the previously cached value.
# If a value has been previously cached for key then it is
# returned. Otherwise, block is yielded to and its return value
# which may be nil, is cached under key and returned.
def fetch(*key)
@cache.fetch(key) do
@cache[key] = yield
end
end
# Clears the cache.
def clear
@cache = {}
end
end
# Base class for all Sinatra applications and middleware.
class Base
include Rack::Utils
include Helpers
include Templates
URI_INSTANCE = defined?(URI::RFC2396_PARSER) ? URI::RFC2396_PARSER : URI::RFC2396_Parser.new
attr_accessor :app, :env, :request, :response, :params
attr_reader :template_cache
def initialize(app = nil, **_kwargs)
super()
@app = app
@template_cache = TemplateCache.new
@pinned_response = nil # whether a before! filter pinned the content-type
yield self if block_given?
end
# Rack call interface.
def call(env)
dup.call!(env)
end
def call!(env) # :nodoc:
@env = env
@params = IndifferentHash.new
@request = Request.new(env)
@response = Response.new