agilis-ads 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgilisAds
4
+ # One page of a cursor-paginated list (`offers.list`, `events.list`,
5
+ # `webhook_events.list`).
6
+ #
7
+ # `page.data` is this page's items. `page.auto_paging_each` yields every item
8
+ # on this page and the pages after it, following `next_cursor` until
9
+ # `has_more` is false; without a block it returns an Enumerator.
10
+ class Page < AgilisObject
11
+ def initialize(values, last_response = nil, fetch_next: nil)
12
+ super(values, last_response)
13
+ @fetch_next = fetch_next
14
+ end
15
+
16
+ def data
17
+ self[:data] || []
18
+ end
19
+
20
+ def pagination
21
+ self[:pagination]
22
+ end
23
+
24
+ # Whether there is another page after this one.
25
+ def more?
26
+ source = pagination || self
27
+ source[:has_more] == true
28
+ end
29
+
30
+ def next_cursor
31
+ source = pagination || self
32
+ source[:next_cursor]
33
+ end
34
+
35
+ # Iterates over this page's items only.
36
+ def each(&)
37
+ return data.each unless block_given?
38
+
39
+ data.each(&)
40
+ self
41
+ end
42
+
43
+ def to_a
44
+ data
45
+ end
46
+
47
+ # The next page, or nil when this is the last one.
48
+ def next_page
49
+ return nil unless more? && next_cursor && @fetch_next
50
+
51
+ @fetch_next.call(next_cursor)
52
+ end
53
+
54
+ # Every item on this page and the following pages.
55
+ def auto_paging_each(&block)
56
+ return enum_for(:auto_paging_each) unless block
57
+
58
+ page = self
59
+ while page
60
+ page.data.each(&block)
61
+ page = page.next_page
62
+ end
63
+ self
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,176 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgilisAds
4
+ # Sends requests: headers, retries, and turning responses into objects or
5
+ # errors. Used by the resources; not part of the public API.
6
+ class Requestor
7
+ NETWORK_ERRORS = [
8
+ AgilisAds::ConnectionError,
9
+ Timeout::Error,
10
+ SocketError,
11
+ SystemCallError,
12
+ IOError,
13
+ OpenSSL::SSL::SSLError,
14
+ Net::ProtocolError,
15
+ Net::HTTPBadResponse
16
+ ].freeze
17
+ RETRYABLE_SERVER_STATUSES = [500, 502, 503, 504].freeze
18
+ INITIAL_RETRY_DELAY = 0.5
19
+ MAX_RETRY_DELAY = 8.0
20
+ REDACTED = "[redacted]"
21
+
22
+ def initialize(api_key:, base_url:, timeout:, max_retries:, http_client:)
23
+ @api_key = api_key
24
+ @base_url = base_url
25
+ @timeout = timeout
26
+ @max_retries = max_retries
27
+ @http_client = http_client
28
+ end
29
+
30
+ def inspect
31
+ "#<#{self.class.name} base_url=#{@base_url.inspect}>"
32
+ end
33
+
34
+ # Sends one call and returns [parsed_body_hash, Response].
35
+ def request(method, path, query: nil, json: nil, multipart: nil, headers: {})
36
+ url = build_url(path, query)
37
+ request_headers = base_headers.merge(headers)
38
+ body = nil
39
+ if multipart
40
+ body, content_type = Multipart.encode(multipart)
41
+ request_headers["Content-Type"] = content_type
42
+ elsif json
43
+ body = JSON.generate(json)
44
+ request_headers["Content-Type"] = "application/json"
45
+ elsif %w[POST PATCH PUT].include?(method)
46
+ request_headers["Content-Length"] = "0"
47
+ end
48
+
49
+ send_with_retries(method, url, request_headers, body)
50
+ end
51
+
52
+ private
53
+
54
+ def send_with_retries(method, url, headers, body)
55
+ idempotent_post = method == "POST" && headers.key?("Idempotency-Key")
56
+ can_retry_server_error = idempotent_post || %w[GET DELETE].include?(method)
57
+ attempt = 0
58
+ loop do
59
+ begin
60
+ status, response_headers, response_body =
61
+ @http_client.call(method: method, url: url, headers: headers, body: body, timeout: @timeout)
62
+ rescue *NETWORK_ERRORS => e
63
+ if attempt < @max_retries
64
+ sleep_before_retry(attempt, nil)
65
+ attempt += 1
66
+ next
67
+ end
68
+ raise connection_error(e)
69
+ end
70
+
71
+ response = Response.new(status, response_headers, response_body)
72
+ if attempt < @max_retries && retryable?(response.status, can_retry_server_error)
73
+ sleep_before_retry(attempt, response.header("retry-after"))
74
+ attempt += 1
75
+ next
76
+ end
77
+
78
+ return handle(response)
79
+ end
80
+ end
81
+
82
+ def retryable?(status, can_retry_server_error)
83
+ status == 429 || (can_retry_server_error && RETRYABLE_SERVER_STATUSES.include?(status))
84
+ end
85
+
86
+ def sleep_before_retry(attempt, retry_after)
87
+ Kernel.sleep(retry_delay(attempt, retry_after))
88
+ end
89
+
90
+ def retry_delay(attempt, retry_after)
91
+ seconds = parse_retry_after(retry_after)
92
+ return seconds if seconds
93
+
94
+ base = [INITIAL_RETRY_DELAY * (2**attempt), MAX_RETRY_DELAY].min
95
+ jitter = (Kernel.rand * 0.5) - 0.25
96
+ [base * (1 + jitter), MAX_RETRY_DELAY].min
97
+ end
98
+
99
+ def parse_retry_after(value)
100
+ return nil if value.nil?
101
+
102
+ seconds = Float(value.to_s.strip, exception: false)
103
+ seconds && seconds >= 0 ? seconds : nil
104
+ end
105
+
106
+ def handle(response)
107
+ parsed = parse_body(response.body)
108
+ return_code = parsed.is_a?(Hash) ? parsed["return_code"] : nil
109
+ success = response.status >= 200 && response.status < 300
110
+ if success && !(return_code.is_a?(String) && return_code.start_with?("E"))
111
+ return [parsed.is_a?(Hash) ? parsed : { "data" => parsed }, response]
112
+ end
113
+
114
+ raise error_for(response, parsed, return_code)
115
+ end
116
+
117
+ def parse_body(body)
118
+ return {} if body.nil? || body.strip.empty?
119
+
120
+ JSON.parse(body.dup.force_encoding(Encoding::UTF_8))
121
+ rescue JSON::ParserError
122
+ nil
123
+ end
124
+
125
+ def error_for(response, parsed, return_code)
126
+ api_message = parsed.is_a?(Hash) ? parsed["message"] : nil
127
+ message = scrub(api_message.is_a?(String) && !api_message.empty? ? api_message : "HTTP #{response.status}")
128
+ options = {
129
+ http_status: response.status,
130
+ return_code: return_code,
131
+ body: parsed.nil? ? response.body : parsed,
132
+ headers: response.headers
133
+ }
134
+ case response.status
135
+ when 200..299, 400, 422 then InvalidRequestError.new(message, **options)
136
+ when 401 then AuthenticationError.new(message, **options)
137
+ when 403 then PermissionError.new(message, **options)
138
+ when 404 then NotFoundError.new(message, **options)
139
+ when 409 then ConflictError.new(message, **options)
140
+ when 429
141
+ RateLimitError.new(message, retry_after: parse_retry_after(response.header("retry-after")), **options)
142
+ else ApiError.new(message, **options)
143
+ end
144
+ end
145
+
146
+ def connection_error(error)
147
+ ConnectionError.new(scrub("Could not reach the Agilis API (#{error.class}: #{error.message})"))
148
+ end
149
+
150
+ def scrub(text)
151
+ return text if @api_key.nil? || @api_key.empty?
152
+
153
+ text.to_s.gsub(@api_key, REDACTED)
154
+ end
155
+
156
+ def base_headers
157
+ {
158
+ "x-api-key" => @api_key,
159
+ "Accept" => "application/json",
160
+ "User-Agent" => "agilis-ads-ruby/#{VERSION} (ruby #{RUBY_VERSION}; #{RUBY_PLATFORM})"
161
+ }
162
+ end
163
+
164
+ def build_url(path, query)
165
+ url = "#{@base_url}#{path}"
166
+ pairs = (query || {}).reject { |_, value| value.nil? }
167
+ return url if pairs.empty?
168
+
169
+ encoded = pairs.map do |name, value|
170
+ value = value.to_s unless value.is_a?(Array)
171
+ [name.to_s, value]
172
+ end
173
+ "#{url}?#{URI.encode_www_form(encoded)}"
174
+ end
175
+ end
176
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgilisAds
4
+ module Resources
5
+ # Shared helpers for the resource classes.
6
+ class Base
7
+ def initialize(client)
8
+ @client = client
9
+ end
10
+
11
+ def inspect
12
+ "#<#{self.class.name}>"
13
+ end
14
+
15
+ private
16
+
17
+ def requestor
18
+ @client.send(:requestor)
19
+ end
20
+
21
+ # Merges a positional params hash with keyword fields; keys become strings
22
+ # and Time values become ISO 8601 UTC strings.
23
+ def merge_params(params, fields)
24
+ merged = {}
25
+ (params || {}).each { |key, value| merged[key.to_s] = normalize(value) }
26
+ fields.each { |key, value| merged[key.to_s] = normalize(value) }
27
+ merged
28
+ end
29
+
30
+ def normalize(value)
31
+ case value
32
+ when Time then value.utc.strftime("%Y-%m-%dT%H:%M:%SZ")
33
+ when Hash then value.to_h { |key, item| [key.to_s, normalize(item)] }
34
+ when Array then value.map { |item| normalize(item) }
35
+ else value
36
+ end
37
+ end
38
+
39
+ # Fills in `environment` from the key's mode when the caller left it out.
40
+ def with_environment(params)
41
+ return params if params.key?("environment") || @client.mode.nil?
42
+
43
+ params.merge("environment" => @client.mode.upcase)
44
+ end
45
+
46
+ def path_segment(value)
47
+ raise ArgumentError, "An id is required" if value.nil? || value.to_s.empty?
48
+
49
+ value.to_s.b.gsub(/[^A-Za-z0-9\-._~]/) { |char| format("%%%02X", char.ord) }
50
+ end
51
+
52
+ def dry_run_query(dry_run)
53
+ dry_run ? { "dry_run" => "true" } : {}
54
+ end
55
+
56
+ def idempotency_headers(idempotency_key)
57
+ { "Idempotency-Key" => (idempotency_key || SecureRandom.uuid).to_s }
58
+ end
59
+
60
+ def call_api(method, path, **options)
61
+ values, response = requestor.request(method, path, **options)
62
+ AgilisObject.new(values, response)
63
+ end
64
+
65
+ def list_page(path, query)
66
+ values, response = requestor.request("GET", path, query: query)
67
+ fetch_next = ->(cursor) { list_page(path, query.merge("cursor" => cursor)) }
68
+ Page.new(values, response, fetch_next: fetch_next)
69
+ end
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgilisAds
4
+ module Resources
5
+ # GET /categories
6
+ class Categories < Base
7
+ def list
8
+ call_api("GET", "/categories")
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgilisAds
4
+ module Resources
5
+ # GET /event-categories
6
+ class EventCategories < Base
7
+ def list
8
+ call_api("GET", "/event-categories")
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgilisAds
4
+ module Resources
5
+ # GET /event-config
6
+ class EventConfig < Base
7
+ def get
8
+ call_api("GET", "/event-config")
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgilisAds
4
+ module Resources
5
+ # GET /event-currencies
6
+ class EventCurrencies < Base
7
+ def list
8
+ call_api("GET", "/event-currencies")
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgilisAds
4
+ module Resources
5
+ # Events: /events
6
+ class Events < Base
7
+ # POST /events/preview (multipart, with the image).
8
+ def preview(params = nil, **fields)
9
+ body = with_environment(merge_params(params, fields))
10
+ call_api("POST", "/events/preview", multipart: body)
11
+ end
12
+
13
+ # POST /events (multipart). Sends an Idempotency-Key: your own
14
+ # `idempotency_key:` or a random UUID, reused on every retry.
15
+ def publish(params = nil, dry_run: false, idempotency_key: nil, **fields)
16
+ body = with_environment(merge_params(params, fields))
17
+ call_api("POST", "/events",
18
+ query: dry_run_query(dry_run), multipart: body, headers: idempotency_headers(idempotency_key))
19
+ end
20
+
21
+ # GET /events: one page. Use `auto_paging_each` on the result for all of them.
22
+ def list(params = nil, **fields)
23
+ list_page("/events", with_environment(merge_params(params, fields)))
24
+ end
25
+
26
+ # GET /events/{event_id}
27
+ def get(event_id)
28
+ call_api("GET", "/events/#{path_segment(event_id)}")
29
+ end
30
+
31
+ # PATCH /events/{event_id} (multipart). Always sent as a POST with
32
+ # `X-HTTP-Method-Override: PATCH`, with or without a new image, because
33
+ # multipart bodies are only read on POST.
34
+ def edit(event_id, params = nil, **fields)
35
+ call_api("POST", "/events/#{path_segment(event_id)}",
36
+ multipart: merge_params(params, fields), headers: { "X-HTTP-Method-Override" => "PATCH" })
37
+ end
38
+
39
+ # DELETE /events/{event_id}
40
+ def delete(event_id, dry_run: false)
41
+ call_api("DELETE", "/events/#{path_segment(event_id)}", query: dry_run_query(dry_run))
42
+ end
43
+
44
+ # POST /events/{event_id}/reschedule (JSON: starts_at, ends_at).
45
+ def reschedule(event_id, params = nil, **fields)
46
+ call_api("POST", "/events/#{path_segment(event_id)}/reschedule", json: merge_params(params, fields))
47
+ end
48
+
49
+ # POST /events/{event_id}/cancel
50
+ def cancel(event_id, dry_run: false)
51
+ call_api("POST", "/events/#{path_segment(event_id)}/cancel", query: dry_run_query(dry_run))
52
+ end
53
+
54
+ # GET /events/{event_id}/analytics
55
+ def analytics(event_id, params = nil, **fields)
56
+ call_api("GET", "/events/#{path_segment(event_id)}/analytics", query: merge_params(params, fields))
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgilisAds
4
+ module Resources
5
+ # GET /interests
6
+ class Interests < Base
7
+ def list
8
+ call_api("GET", "/interests")
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgilisAds
4
+ module Resources
5
+ # Offers: /offers
6
+ class Offers < Base
7
+ # POST /offers/price-estimate (JSON).
8
+ def estimate_price(params = nil, **fields)
9
+ body = with_environment(merge_params(params, fields))
10
+ call_api("POST", "/offers/price-estimate", json: body)
11
+ end
12
+
13
+ # POST /offers (multipart, with the image). Sends an Idempotency-Key: your
14
+ # own `idempotency_key:` or a random UUID, reused on every retry.
15
+ def create(params = nil, dry_run: false, idempotency_key: nil, **fields)
16
+ body = with_environment(merge_params(params, fields))
17
+ call_api("POST", "/offers",
18
+ query: dry_run_query(dry_run), multipart: body, headers: idempotency_headers(idempotency_key))
19
+ end
20
+
21
+ # GET /offers: one page. Use `auto_paging_each` on the result for all of them.
22
+ def list(params = nil, **fields)
23
+ list_page("/offers", with_environment(merge_params(params, fields)))
24
+ end
25
+
26
+ # POST /offers/{offer_id}/pause
27
+ def pause(offer_id)
28
+ call_api("POST", "/offers/#{path_segment(offer_id)}/pause")
29
+ end
30
+
31
+ # POST /offers/{offer_id}/resume
32
+ def resume(offer_id)
33
+ call_api("POST", "/offers/#{path_segment(offer_id)}/resume")
34
+ end
35
+
36
+ # GET /offers/{offer_id}/analytics
37
+ def analytics(offer_id, params = nil, **fields)
38
+ call_api("GET", "/offers/#{path_segment(offer_id)}/analytics", query: merge_params(params, fields))
39
+ end
40
+
41
+ # DELETE /offers/{offer_id}
42
+ def delete(offer_id, dry_run: false)
43
+ call_api("DELETE", "/offers/#{path_segment(offer_id)}", query: dry_run_query(dry_run))
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgilisAds
4
+ module Resources
5
+ # Webhook endpoints: /webhook-endpoints
6
+ class WebhookEndpoints < Base
7
+ # GET /webhook-endpoints
8
+ def list
9
+ call_api("GET", "/webhook-endpoints")
10
+ end
11
+
12
+ # POST /webhook-endpoints (JSON). The response holds `secret`, shown only this once.
13
+ def create(params = nil, **fields)
14
+ call_api("POST", "/webhook-endpoints", json: merge_params(params, fields))
15
+ end
16
+
17
+ # GET /webhook-endpoints/{endpoint_id}
18
+ def get(endpoint_id)
19
+ call_api("GET", "/webhook-endpoints/#{path_segment(endpoint_id)}")
20
+ end
21
+
22
+ # PATCH /webhook-endpoints/{endpoint_id} (JSON).
23
+ def update(endpoint_id, params = nil, **fields)
24
+ call_api("PATCH", "/webhook-endpoints/#{path_segment(endpoint_id)}", json: merge_params(params, fields))
25
+ end
26
+
27
+ # DELETE /webhook-endpoints/{endpoint_id}
28
+ def delete(endpoint_id)
29
+ call_api("DELETE", "/webhook-endpoints/#{path_segment(endpoint_id)}")
30
+ end
31
+
32
+ # POST /webhook-endpoints/{endpoint_id}/roll-secret (JSON, optional expires_in).
33
+ def roll_secret(endpoint_id, params = nil, **fields)
34
+ call_api("POST", "/webhook-endpoints/#{path_segment(endpoint_id)}/roll-secret",
35
+ json: merge_params(params, fields))
36
+ end
37
+
38
+ # POST /webhook-endpoints/{endpoint_id}/test (JSON, optional type).
39
+ def send_test(endpoint_id, params = nil, **fields)
40
+ call_api("POST", "/webhook-endpoints/#{path_segment(endpoint_id)}/test", json: merge_params(params, fields))
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgilisAds
4
+ module Resources
5
+ # Webhook events: /webhook-events
6
+ class WebhookEvents < Base
7
+ # GET /webhook-events: one page. Use `auto_paging_each` on the result for all of them.
8
+ def list(params = nil, **fields)
9
+ list_page("/webhook-events", merge_params(params, fields))
10
+ end
11
+
12
+ # GET /webhook-events/{webhook_event_id}
13
+ def get(webhook_event_id)
14
+ call_api("GET", "/webhook-events/#{path_segment(webhook_event_id)}")
15
+ end
16
+
17
+ # POST /webhook-events/{webhook_event_id}/resend (JSON, optional endpoint_id).
18
+ def resend(webhook_event_id, params = nil, **fields)
19
+ call_api("POST", "/webhook-events/#{path_segment(webhook_event_id)}/resend",
20
+ json: merge_params(params, fields))
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgilisAds
4
+ module Resources
5
+ # `client.webhooks.construct_event` is the same as AgilisAds::Webhook.construct_event.
6
+ class Webhooks < Base
7
+ def construct_event(raw_body, signature_header, secret, tolerance = Webhook::DEFAULT_TOLERANCE, now: nil)
8
+ Webhook.construct_event(raw_body, signature_header, secret, tolerance, now: now)
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgilisAds
4
+ # The HTTP status, headers and raw body of an API response.
5
+ class Response
6
+ attr_reader :status, :headers, :body
7
+
8
+ def initialize(status, headers, body)
9
+ @status = status.to_i
10
+ @headers = (headers || {}).to_h { |name, value| [name.to_s.downcase, Array(value).join(", ")] }
11
+ @body = body.to_s
12
+ end
13
+
14
+ # A header by name, case-insensitively, or nil.
15
+ def header(name)
16
+ @headers[name.to_s.downcase]
17
+ end
18
+
19
+ def rate_limit_limit
20
+ integer_header("x-ratelimit-limit")
21
+ end
22
+
23
+ def rate_limit_remaining
24
+ integer_header("x-ratelimit-remaining")
25
+ end
26
+
27
+ def inspect
28
+ "#<#{self.class.name} status=#{@status}>"
29
+ end
30
+
31
+ private
32
+
33
+ def integer_header(name)
34
+ value = header(name)
35
+ value && Integer(value, exception: false)
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgilisAds
4
+ # A file to send in a multipart request, such as an Offer or Event image.
5
+ #
6
+ # AgilisAds::Upload.from_path("offer.png")
7
+ # AgilisAds::Upload.from_bytes(png_bytes, filename: "offer.png")
8
+ # AgilisAds::Upload.from_io(File.open("offer.png", "rb"))
9
+ #
10
+ # Anywhere an upload is accepted you can also pass a file path (String or
11
+ # Pathname) or an open IO; the content type is detected from the file name.
12
+ class Upload
13
+ CONTENT_TYPES = {
14
+ ".jpg" => "image/jpeg",
15
+ ".jpeg" => "image/jpeg",
16
+ ".png" => "image/png",
17
+ ".gif" => "image/gif",
18
+ ".webp" => "image/webp"
19
+ }.freeze
20
+ DEFAULT_CONTENT_TYPE = "application/octet-stream"
21
+
22
+ attr_reader :filename, :content_type
23
+
24
+ def self.from_path(path, filename: nil, content_type: nil)
25
+ path = path.to_s
26
+ new(-> { File.binread(path) }, filename: filename || File.basename(path), content_type: content_type)
27
+ end
28
+
29
+ def self.from_bytes(bytes, filename:, content_type: nil)
30
+ new(-> { bytes.to_s.b }, filename: filename, content_type: content_type)
31
+ end
32
+
33
+ def self.from_io(io, filename: nil, content_type: nil)
34
+ name = filename || (io.respond_to?(:path) && io.path ? File.basename(io.path.to_s) : "upload")
35
+ new(-> { io.read.to_s.b }, filename: name, content_type: content_type)
36
+ end
37
+
38
+ # Converts a path, IO or Upload into an Upload.
39
+ def self.coerce(value)
40
+ case value
41
+ when Upload then value
42
+ when String, Pathname then from_path(value)
43
+ else
44
+ raise ArgumentError, "Cannot upload a #{value.class}" unless value.respond_to?(:read)
45
+
46
+ from_io(value)
47
+ end
48
+ end
49
+
50
+ def self.upload?(value)
51
+ value.is_a?(Upload) || value.is_a?(Pathname) || (!value.is_a?(String) && value.respond_to?(:read))
52
+ end
53
+
54
+ def self.content_type_for(filename)
55
+ CONTENT_TYPES.fetch(File.extname(filename.to_s).downcase, DEFAULT_CONTENT_TYPE)
56
+ end
57
+
58
+ def initialize(reader, filename:, content_type: nil)
59
+ @reader = reader
60
+ @filename = filename.to_s
61
+ @content_type = content_type || self.class.content_type_for(@filename)
62
+ end
63
+
64
+ # The file's bytes (read once).
65
+ def read
66
+ @read ||= @reader.call.b
67
+ end
68
+
69
+ def inspect
70
+ "#<#{self.class.name} filename=#{@filename.inspect} content_type=#{@content_type.inspect}>"
71
+ end
72
+ end
73
+ end