This repository has been archived by the owner on Jul 13, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
url_generator.rb
75 lines (63 loc) · 1.74 KB
/
url_generator.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
require 'uri'
module Paperclip
class UrlGenerator
def initialize(attachment)
@attachment = attachment
end
def for(style_name, options)
interpolated = attachment_options[:interpolator].interpolate(
most_appropriate_url, @attachment, style_name
)
escaped = escape_url_as_needed(interpolated, options)
timestamp_as_needed(escaped, options)
end
private
attr_reader :attachment
delegate :options, to: :attachment, prefix: true
# This method is all over the place.
def default_url
if attachment_options[:default_url].respond_to?(:call)
attachment_options[:default_url].call(@attachment)
elsif attachment_options[:default_url].is_a?(Symbol)
@attachment.instance.send(attachment_options[:default_url])
else
attachment_options[:default_url]
end
end
def most_appropriate_url
if @attachment.original_filename.nil?
default_url
else
attachment_options[:url]
end
end
def timestamp_as_needed(url, options)
if options[:timestamp] && timestamp_possible?
delimiter_char = url.match(/\?.+=/) ? '&' : '?'
"#{url}#{delimiter_char}#{@attachment.updated_at.to_s}"
else
url
end
end
def timestamp_possible?
@attachment.respond_to?(:updated_at) && @attachment.updated_at.present?
end
def escape_url_as_needed(url, options)
if options[:escape]
escape_url(url)
else
url
end
end
def escape_url(url)
if url.respond_to?(:escape)
url.escape
else
URI.escape(url).gsub(escape_regex){|m| "%#{m.ord.to_s(16).upcase}" }
end
end
def escape_regex
/[\?\(\)\[\]\+]/
end
end
end