buttondown 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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: a2f59e3496b1145cd2259c6fe162457267cd9ee8b1462d7038632bafb25c3454
4
+ data.tar.gz: aeaca0b5b4293c823f5d5299a651dab30e9f1c387bfb40deb5c5a6dab30bb529
5
+ SHA512:
6
+ metadata.gz: 237606ede94e6bf9edaa6174e7aed6aec8f00928aef1480ec97d0bcb373f745644724598f3aaccb29b67d59437ad5500a37aa46fa98cc587f206230cf5e46f12
7
+ data.tar.gz: 713bdc8b9131a48a3d945c7b11e0ce2df97f81e07230d65c2fdda2170dd510d1b6beb23c81a2185fa7067f2490d5a43410917dbd227d4897cd029bdbf40f2cf7
data/.rubocop.yml ADDED
@@ -0,0 +1,48 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.3
3
+ NewCops: enable
4
+ SuggestExtensions: false
5
+
6
+ # Style choices, not quality ones. These match the code as written and the
7
+ # other gems in the house; RuboCop's defaults simply differ from standard's.
8
+ Style/StringLiterals:
9
+ EnforcedStyle: double_quotes
10
+
11
+ Style/StringLiteralsInInterpolation:
12
+ EnforcedStyle: double_quotes
13
+
14
+ Layout/SpaceInsideHashLiteralBraces:
15
+ EnforcedStyle: no_space
16
+
17
+ Layout/MultilineMethodCallIndentation:
18
+ EnforcedStyle: indented
19
+
20
+ Layout/MultilineOperationIndentation:
21
+ EnforcedStyle: indented
22
+
23
+ # Classes here carry comments where a comment earns its place. A cop that
24
+ # demands one directly above every class just produces filler.
25
+ Style/Documentation:
26
+ Enabled: false
27
+
28
+ # The cop exists to stop long positional lists, where order is a trap.
29
+ # Keyword arguments have no such problem.
30
+ Metrics/ParameterLists:
31
+ CountKeywordArgs: false
32
+
33
+ # A test file is one long block of `describe`/`it` by construction. Measuring
34
+ # its length says nothing about whether it is well organized.
35
+ Metrics/BlockLength:
36
+ Exclude:
37
+ - 'test/**/*'
38
+
39
+ # A little above the defaults. An HTTP client that builds a request and
40
+ # classifies every response shape is cohesive at this size; splitting it
41
+ # further to satisfy the default would spread one job across more files.
42
+ Metrics/MethodLength:
43
+ Max: 15
44
+
45
+ Metrics/ClassLength:
46
+ Max: 150
47
+ Exclude:
48
+ - 'test/**/*'
data/.undercover ADDED
@@ -0,0 +1 @@
1
+ --include-files lib/**/*.rb
data/CHANGELOG.md ADDED
@@ -0,0 +1,28 @@
1
+ # Changelog
2
+
3
+ All notable changes to this gem are documented here. The error classes are part
4
+ of the public API -- callers rescue them by name -- so every change to the error
5
+ hierarchy is listed.
6
+
7
+ ## Unreleased
8
+
9
+ - Added `Buttondown::EmailAlreadyExistsError` and
10
+ `Buttondown::SubscriberBlockedError`, both subclasses of
11
+ `Buttondown::BadRequestError`, mapped from the `email_already_exists` and
12
+ `subscriber_blocked` codes. Previously both surfaced as plain
13
+ `BadRequestError`; existing rescues keep working.
14
+
15
+ ## 0.1.0 - 2026-11-21
16
+
17
+ Initial release.
18
+
19
+ - `Buttondown::Client#subscribe`, covering `POST /v1/subscribers`
20
+ - Token from the constructor, defaulting to `ENV["BUTTONDOWN_API_KEY"]`; a blank
21
+ token raises `Buttondown::ConfigurationError` at construction
22
+ - `type:` defaults to `"regular"`, skipping Buttondown's double opt-in for the
23
+ subscriber. Pass `nil` to let Buttondown's own default apply
24
+ - `collision_behavior:` defaults to `"add"`, merging a duplicate instead of
25
+ failing. Pass `nil` to make a duplicate raise
26
+ - Returns a `Buttondown::Subscriber`
27
+ - Full error hierarchy under `Buttondown::Error`
28
+ - No runtime dependencies; Net::HTTP from stdlib
data/Gemfile ADDED
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in buttondown.gemspec
6
+ gemspec
7
+
8
+ gem "bundler-audit", "~> 0.9"
9
+ gem "gem-release", "~> 2.2"
10
+ gem "guard", "~> 2.18"
11
+ gem "guard-minitest", "~> 3.0"
12
+ gem "guard-rubocop", "~> 1.5"
13
+ gem "minitest", "~> 6.1"
14
+ gem "minitest-reporters", "~> 1.3"
15
+ gem "mocha", "~> 3.1.0"
16
+ gem "rake", "~> 13.0"
17
+ gem "rubocop", "~> 1.92"
18
+ gem "simplecov", "~> 1.3", require: false
19
+ gem "simplecov-lcov", "~> 0.8", require: false
20
+ gem "undercover", "~> 0.9", require: false
21
+ gem "webmock", "~> 3.23"
data/Guardfile ADDED
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ guard :rubocop, all_on_start: false do
4
+ watch(/.+\.rb$/)
5
+ end
6
+
7
+ guard :minitest, all_on_start: false do
8
+ watch(%r{^test/(.*/)?([^/]+)_test\.rb$})
9
+ watch(%r{^lib/(.*/)?([^/]+)\.rb$}) do |m|
10
+ "test/#{m[1]}#{m[2]}_test.rb"
11
+ end
12
+ watch(%r{^test/test_helper\.rb$}) { "test" }
13
+ end
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Nick Hammond
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,182 @@
1
+ # Buttondown
2
+
3
+ A Ruby client for the [Buttondown](https://buttondown.com) newsletter API.
4
+
5
+ No runtime dependencies — just Net::HTTP from the standard library.
6
+
7
+ ### Built for Shipyrd
8
+
9
+ This gem was extracted from [Shipyrd](https://shipyrd.io), a deployment dashboard
10
+ for Kamal that shows you what shipped, when, and by whom. If you deploy with
11
+ Kamal, [give Shipyrd a look](https://shipyrd.io).
12
+
13
+ ## Installation
14
+
15
+ ```ruby
16
+ gem "buttondown"
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ```ruby
22
+ client = Buttondown::Client.new # reads ENV["BUTTONDOWN_API_KEY"]
23
+ client = Buttondown::Client.new("your-key") # or pass it explicitly
24
+
25
+ subscriber = client.subscribe("subscriber@example.com")
26
+ subscriber.regular? # => true
27
+ ```
28
+
29
+ ### Options
30
+
31
+ Two keywords have defaults, so the call above is the same as writing:
32
+
33
+ ```ruby
34
+ client.subscribe(email, type: "regular", collision_behavior: "add")
35
+ ```
36
+
37
+ `type:` is the state the subscriber starts in.
38
+
39
+ | Value | Effect |
40
+ |---|---|
41
+ | `"regular"` (default) | Subscribed immediately, skipping Buttondown's double opt-in |
42
+ | `nil` | Sends no type, so Buttondown's own default applies: `"unactivated"` until they confirm by email |
43
+
44
+ `collision_behavior:` decides what happens when the address is already a
45
+ subscriber. It travels as the `X-Buttondown-Collision-Behavior` header.
46
+
47
+ | Value | Effect |
48
+ |---|---|
49
+ | `"add"` (default) | Merges into the existing subscriber and returns it, so a duplicate is a success |
50
+ | `"overwrite"` | Replaces the existing data. A terminal subscriber raises `SubscriberSuppressedError` |
51
+ | `nil` | Omits the header, so a duplicate raises `EmailAlreadyExistsError` — the only way to detect "already subscribed" |
52
+
53
+ What Buttondown does with those values — opt-in states, how collisions resolve,
54
+ rate limits — is documented at [docs.buttondown.com](https://docs.buttondown.com).
55
+
56
+ ### The subscriber
57
+
58
+ `subscribe` returns a `Buttondown::Subscriber`, a thin read-only view of the
59
+ JSON Buttondown sent back:
60
+
61
+ ```ruby
62
+ subscriber = client.subscribe("subscriber@example.com")
63
+
64
+ subscriber.id # => "sub_..." (a TypeID on 2026-01-01 and later)
65
+ subscriber.email_address # => "subscriber@example.com"
66
+ subscriber.type # => "regular"
67
+ subscriber.to_h # the raw parsed body
68
+ ```
69
+
70
+ Because a merged duplicate also comes back as a success, returning the
71
+ pre-existing record, check the type before assuming the address is active:
72
+
73
+ ```ruby
74
+ subscriber.regular? # will receive email
75
+ subscriber.unactivated? # created, not yet confirmed
76
+ subscriber.terminal? # unsubscribed, blocked, complained or undeliverable
77
+ ```
78
+
79
+ Fields without a reader stay reachable, so a new API field doesn't need a gem
80
+ release:
81
+
82
+ ```ruby
83
+ subscriber[:creation_date]
84
+ ```
85
+
86
+ ### Errors
87
+
88
+ Everything the gem raises descends from `Buttondown::Error`, so one rescue is
89
+ enough to be safe. Rescue the specific classes where you want to act differently.
90
+
91
+ | Class | Raised when | Safe to retry? |
92
+ |---|---|---|
93
+ | `ConfigurationError` | No token at construction | No — fix the config |
94
+ | `InvalidEmailError` | Blank or obviously malformed address. **No request is made** | No |
95
+ | `SubscriberSuppressedError` | 400 with the `subscriber_suppressed` code | No |
96
+ | `EmailAlreadyExistsError` | 400 with the `email_already_exists` code. Only with `collision_behavior: nil` | No |
97
+ | `SubscriberBlockedError` | 400 with the `subscriber_blocked` code — Buttondown's firewall rejected the address | No |
98
+ | `BadRequestError` | A validation failure. Read `#code` and `#body` | No |
99
+ | `AuthenticationError` | 401 | No |
100
+ | `FeatureDisabledError` | 403 with the `feature_disabled` code | No |
101
+ | `ForbiddenError` | Any other 403 | No |
102
+ | `NotFoundError` | 404 | No |
103
+ | `UnprocessableEntityError` | 422 | No |
104
+ | `RateLimitError` | 429. Exposes `#retry_after` when the header is sent | Yes, after a wait |
105
+ | `ServerError` | 5xx | Yes |
106
+ | `TimeoutError` | Connect, read or write timed out | Yes |
107
+ | `ConnectionError` | DNS, TLS or socket failure | Yes |
108
+ | `InvalidResponseError` | A 2xx whose body wasn't usable JSON | Yes |
109
+
110
+ Every HTTP error carries `#status`, `#code`, `#body`, `#raw_body` and `#headers`:
111
+
112
+ ```ruby
113
+ begin
114
+ client.subscribe(email)
115
+ rescue Buttondown::SubscriberSuppressedError
116
+ # terminal; retrying won't help
117
+ rescue Buttondown::RateLimitError => e
118
+ retry_in(e.retry_after || 1.hour)
119
+ rescue Buttondown::ConnectionError, Buttondown::ServerError
120
+ retry_later # the default collision behavior makes this idempotent
121
+ rescue Buttondown::APIError => e
122
+ report(status: e.status, code: e.code, body: e.body)
123
+ end
124
+ ```
125
+
126
+ Connection failures are wrapped, but the original exception is preserved as
127
+ `#cause` if you need it.
128
+
129
+ In Rails, that makes the retry policy for a job a single line:
130
+
131
+ ```ruby
132
+ retry_on Buttondown::ConnectionError, Buttondown::ServerError
133
+ discard_on Buttondown::SubscriberSuppressedError, Buttondown::InvalidEmailError
134
+ ```
135
+
136
+ Email validation before the request is deliberately loose, so the gem is never
137
+ stricter than the API itself. One consequence: dotless hosts like
138
+ `user@localhost` are rejected.
139
+
140
+ ### API version
141
+
142
+ Requests pin `X-API-Version: 2026-04-01`. Override it per client:
143
+
144
+ ```ruby
145
+ Buttondown::Client.new(token, api_version: "2025-01-01")
146
+ ```
147
+
148
+ Timeouts are configurable the same way — `open_timeout:` (default 5s),
149
+ `read_timeout:` and `write_timeout:` (default 10s).
150
+
151
+ ## Development
152
+
153
+ After checking out the repo, run `bin/setup` to install dependencies, then
154
+ `bin/console` for an interactive prompt.
155
+
156
+ `bin/ci` runs everything CI runs — tests, RuboCop, undercover and
157
+ bundler-audit. `bin/test` runs just the tests.
158
+
159
+ ## Releasing a new version
160
+
161
+ Update `CHANGELOG.md`, then from a clean `main`:
162
+
163
+ ```
164
+ bin/release 0.1.1
165
+ ```
166
+
167
+ That runs `bin/ci`, bumps `lib/buttondown/version.rb`, tags, and pushes the
168
+ gem. One-time setup: `gem signin`.
169
+
170
+ ## Contributing
171
+
172
+ Bug reports and pull requests are welcome at
173
+ https://github.com/nickhammond/buttondown.
174
+
175
+ ## License
176
+
177
+ Available as open source under the terms of the [MIT License](LICENSE.txt).
178
+
179
+ ---
180
+
181
+ Built and maintained alongside [Shipyrd](https://shipyrd.io) — deployment
182
+ dashboards for Kamal.
data/Rakefile ADDED
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+ require "rubocop/rake_task"
6
+
7
+ Rake::TestTask.new(:test) do |t|
8
+ t.libs << "test"
9
+ t.libs << "lib"
10
+ t.test_files = FileList["test/**/*_test.rb"]
11
+ end
12
+
13
+ RuboCop::RakeTask.new
14
+
15
+ task default: %i[test rubocop]
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/buttondown/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "buttondown"
7
+ spec.version = Buttondown::VERSION
8
+ spec.authors = ["Nick Kelly"]
9
+ spec.email = ["nick@fromthekeyboard.com"]
10
+
11
+ spec.summary = "Ruby client for the Buttondown newsletter API"
12
+ spec.description = "A Ruby client for the Buttondown newsletter API."
13
+ spec.homepage = "https://github.com/nickhammond/buttondown"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 3.3.0"
16
+
17
+ spec.metadata["homepage_uri"] = spec.homepage
18
+ spec.metadata["source_code_uri"] = "https://github.com/nickhammond/buttondown"
19
+ spec.metadata["changelog_uri"] = "https://github.com/nickhammond/buttondown/blob/main/CHANGELOG.md"
20
+ spec.metadata["bug_tracker_uri"] = "https://github.com/nickhammond/buttondown/issues"
21
+ spec.metadata["rubygems_mfa_required"] = "true"
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(__dir__) do
26
+ `git ls-files -z`.split("\x0").reject do |f|
27
+ (File.expand_path(f) == __FILE__) || f.start_with?(*%w[bin/ test/ spec/ features/ .git])
28
+ end
29
+ end
30
+
31
+ spec.require_paths = ["lib"]
32
+ end
@@ -0,0 +1,210 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Buttondown
4
+ class Client
5
+ BASE_URL = "https://api.buttondown.com/v1"
6
+
7
+ # Pins the API version. Unpinned requests use whatever version is set on the
8
+ # account's settings page, which can change under you.
9
+ API_VERSION = "2026-04-01"
10
+
11
+ # "regular" opts the subscriber in directly, skipping Buttondown's double
12
+ # opt-in for this subscriber.
13
+ DEFAULT_TYPE = "regular"
14
+
15
+ # "add" merges a repeat subscribe into the existing subscriber instead of
16
+ # returning a 400.
17
+ DEFAULT_COLLISION_BEHAVIOR = "add"
18
+
19
+ OPEN_TIMEOUT = 5
20
+ READ_TIMEOUT = 10
21
+ WRITE_TIMEOUT = 10
22
+
23
+ USER_AGENT = "buttondown-rb/#{VERSION}".freeze
24
+
25
+ # Deliberately permissive: never stricter than Buttondown itself. Rejects
26
+ # only what no mail server would accept. Known false negative: dotless hosts
27
+ # such as "user@localhost".
28
+ EMAIL_PATTERN = /\A[^@\s]+@[^@\s]+\.[^@\s]+\z/
29
+
30
+ # Listed first, because these are also Timeout::Error descendants and Ruby
31
+ # takes the first matching rescue clause.
32
+ TIMEOUT_ERRORS = [
33
+ Net::OpenTimeout,
34
+ Net::ReadTimeout,
35
+ Net::WriteTimeout
36
+ ].freeze
37
+
38
+ CONNECTION_ERRORS = [
39
+ SocketError,
40
+ EOFError,
41
+ IOError,
42
+ Errno::ECONNREFUSED,
43
+ Errno::ECONNRESET,
44
+ Errno::EHOSTUNREACH,
45
+ Errno::ENETUNREACH,
46
+ Errno::ETIMEDOUT,
47
+ Errno::EPIPE,
48
+ OpenSSL::SSL::SSLError
49
+ ].freeze
50
+
51
+ attr_reader :token, :api_version
52
+
53
+ def initialize(token = ENV.fetch("BUTTONDOWN_API_KEY", nil),
54
+ api_version: API_VERSION,
55
+ open_timeout: OPEN_TIMEOUT,
56
+ read_timeout: READ_TIMEOUT,
57
+ write_timeout: WRITE_TIMEOUT)
58
+ @token = token.to_s.strip
59
+
60
+ if @token.empty?
61
+ raise ConfigurationError,
62
+ 'No Buttondown API token. Pass one to Buttondown::Client.new or set ENV["BUTTONDOWN_API_KEY"].'
63
+ end
64
+
65
+ @api_version = api_version
66
+ @open_timeout = open_timeout
67
+ @read_timeout = read_timeout
68
+ @write_timeout = write_timeout
69
+ end
70
+
71
+ # Creates a subscriber. Returns a Buttondown::Subscriber.
72
+ #
73
+ # type: "regular" (default) skips Buttondown's double opt-in
74
+ # for this subscriber. Pass nil to let Buttondown apply
75
+ # its own default, leaving them "unactivated" until
76
+ # they confirm by email.
77
+ # collision_behavior: "add" (default) merges into an existing subscriber
78
+ # instead of failing. "overwrite" replaces. nil omits
79
+ # the header, so a duplicate raises BadRequestError --
80
+ # the only way to detect "already subscribed".
81
+ #
82
+ # Because "add" turns a duplicate into a success returning the pre-existing
83
+ # record, a successful call does NOT mean this person will receive email.
84
+ # Check Subscriber#regular?.
85
+ def subscribe(email, type: DEFAULT_TYPE, collision_behavior: DEFAULT_COLLISION_BEHAVIOR)
86
+ payload = {email_address: normalize_email(email)}
87
+ payload[:type] = type if type
88
+
89
+ Subscriber.new(post("/subscribers", payload, collision_behavior: collision_behavior))
90
+ end
91
+
92
+ # Keeps the token out of logs, error-tracker breadcrumbs and binding.irb.
93
+ def inspect
94
+ "#<#{self.class.name} api_version=#{api_version.inspect} token=[FILTERED]>"
95
+ end
96
+
97
+ private
98
+
99
+ def post(path, payload, collision_behavior: nil)
100
+ # Interpolated, not URI.join -- join would replace "/v1" and silently drop
101
+ # the version prefix.
102
+ uri = URI("#{BASE_URL}#{path}")
103
+
104
+ request = Net::HTTP::Post.new(uri.request_uri, request_headers(collision_behavior))
105
+ request.body = JSON.generate(payload)
106
+
107
+ handle(perform(build_http(uri), request))
108
+ end
109
+
110
+ def build_http(uri)
111
+ http = Net::HTTP.new(uri.host, uri.port)
112
+ http.use_ssl = uri.scheme == "https"
113
+ http.open_timeout = @open_timeout
114
+ http.read_timeout = @read_timeout
115
+ http.write_timeout = @write_timeout
116
+ http.max_retries = 0 # never silently re-POST against a rate-limited endpoint
117
+ http
118
+ end
119
+
120
+ # Rescues an explicit list rather than bare `rescue`, so a bug in this gem
121
+ # surfaces as itself instead of being reported as a connection failure.
122
+ def perform(http, request)
123
+ http.request(request)
124
+ rescue *TIMEOUT_ERRORS => e
125
+ raise TimeoutError, "Buttondown request timed out: #{e.class}"
126
+ rescue *CONNECTION_ERRORS => e
127
+ raise ConnectionError, "Couldn't reach Buttondown: #{e.class}: #{e.message}"
128
+ end
129
+
130
+ def request_headers(collision_behavior)
131
+ headers = {
132
+ "Authorization" => "Token #{token}",
133
+ "Content-Type" => "application/json",
134
+ "Accept" => "application/json",
135
+ "User-Agent" => USER_AGENT,
136
+ "X-API-Version" => api_version
137
+ }
138
+ headers["X-Buttondown-Collision-Behavior"] = collision_behavior.to_s if collision_behavior
139
+ headers
140
+ end
141
+
142
+ # Returns the parsed body Hash on success; raises otherwise.
143
+ def handle(response)
144
+ status = response.code.to_i
145
+ raw_body = response.body.to_s
146
+
147
+ return success_body(status, raw_body) if response.is_a?(Net::HTTPSuccess)
148
+
149
+ raise_api_error(response, status, raw_body)
150
+ end
151
+
152
+ def success_body(status, raw_body)
153
+ return {} if raw_body.empty?
154
+
155
+ parsed = parse_json(raw_body)
156
+ return parsed if parsed.is_a?(Hash)
157
+
158
+ raise InvalidResponseError.new(
159
+ "Buttondown returned a #{status} whose body wasn't a JSON object",
160
+ status: status,
161
+ raw_body: raw_body
162
+ )
163
+ end
164
+
165
+ def raise_api_error(response, status, raw_body)
166
+ parsed = parse_json(raw_body)
167
+ parsed = {} unless parsed.is_a?(Hash)
168
+
169
+ code = parsed["code"] || parsed["error_code"]
170
+ message = parsed["detail"] || parsed["error"] || parsed["message"] || response.message
171
+
172
+ raise error_class_for(code, status).new(
173
+ message,
174
+ status: status,
175
+ code: code,
176
+ body: parsed,
177
+ raw_body: raw_body,
178
+ headers: response.to_hash.transform_values(&:first)
179
+ )
180
+ end
181
+
182
+ # Code before status: a code is more specific than the status carrying it.
183
+ def error_class_for(code, status)
184
+ ERROR_CODES[code] || STATUS_ERRORS[status] || (status >= 500 ? ServerError : APIError)
185
+ end
186
+
187
+ def parse_json(string)
188
+ JSON.parse(string)
189
+ rescue JSON::ParserError
190
+ nil
191
+ end
192
+
193
+ # Stands in for the Rails-flavored blank check the extracted code used, and
194
+ # guards a 100/day rate limit against addresses no mail server would accept.
195
+ #
196
+ # This message omits the address, but that is a local courtesy rather than a
197
+ # gem-wide guarantee: Buttondown quotes the address back in its own error
198
+ # `detail` (see `email_already_exists`) and APIError#to_s passes that
199
+ # through unchanged. Scrub at the error-tracker boundary if messages must
200
+ # be address-free.
201
+ def normalize_email(email)
202
+ value = email.to_s.strip
203
+
204
+ raise InvalidEmailError, "Email address can't be blank" if value.empty?
205
+ raise InvalidEmailError, "Email address isn't a valid address" unless value.match?(EMAIL_PATTERN)
206
+
207
+ value
208
+ end
209
+ end
210
+ end
@@ -0,0 +1,107 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Buttondown
4
+ # Base class for everything this gem raises. `rescue Buttondown::Error` is the
5
+ # whole contract -- no Net::HTTP or JSON exception escapes the client.
6
+ class Error < StandardError; end
7
+
8
+ # No token was passed and ENV["BUTTONDOWN_API_KEY"] is unset or blank.
9
+ class ConfigurationError < Error; end
10
+
11
+ # A bad argument, caught locally. No HTTP request was made.
12
+ class InvalidArgumentError < Error; end
13
+
14
+ class InvalidEmailError < InvalidArgumentError; end
15
+
16
+ # The request never produced a complete HTTP response.
17
+ class ConnectionError < Error; end
18
+
19
+ class TimeoutError < ConnectionError; end
20
+
21
+ # Buttondown answered 2xx but the body wasn't a JSON object we could use -- a
22
+ # proxy maintenance page, or a truncated response.
23
+ class InvalidResponseError < Error
24
+ attr_reader :status, :raw_body
25
+
26
+ def initialize(message, status: nil, raw_body: nil)
27
+ @status = status
28
+ @raw_body = raw_body
29
+ super(message)
30
+ end
31
+ end
32
+
33
+ # Buttondown answered with a non-2xx status.
34
+ #
35
+ # Exposes the response as plain data (`headers`, `raw_body`) rather than the
36
+ # Net::HTTPResponse itself, so swapping the HTTP backend stays a patch release.
37
+ class APIError < Error
38
+ attr_reader :status, :code, :body, :raw_body, :headers
39
+
40
+ def initialize(message, status: nil, code: nil, body: nil, raw_body: nil, headers: nil)
41
+ @status = status
42
+ @code = code
43
+ @body = body || {}
44
+ @raw_body = raw_body
45
+ @headers = headers || {}
46
+ super(message)
47
+ end
48
+
49
+ def to_s
50
+ [super, code && "(#{code})", status && "[HTTP #{status}]"].compact.join(" ")
51
+ end
52
+ end
53
+
54
+ class BadRequestError < APIError; end
55
+
56
+ class SubscriberSuppressedError < BadRequestError; end
57
+
58
+ # The address is already a subscriber. Only reachable with
59
+ # `collision_behavior: nil` -- "add" and "overwrite" merge instead of
60
+ # failing, so they never raise this.
61
+ class EmailAlreadyExistsError < BadRequestError; end
62
+
63
+ # Buttondown's firewall rejected the address before creating anything:
64
+ # a reserved domain such as example.com, a disposable provider, or too high
65
+ # a risk score. Retrying the same address will fail the same way.
66
+ class SubscriberBlockedError < BadRequestError; end
67
+
68
+ class AuthenticationError < APIError; end
69
+
70
+ class ForbiddenError < APIError; end
71
+
72
+ class FeatureDisabledError < ForbiddenError; end
73
+
74
+ class NotFoundError < APIError; end
75
+
76
+ class UnprocessableEntityError < APIError; end
77
+
78
+ class ServerError < APIError; end
79
+
80
+ class RateLimitError < APIError
81
+ # Seconds to wait, when Buttondown tells us. Nil otherwise -- the 100/day
82
+ # subscriber-creation limit often comes back without a hint.
83
+ def retry_after
84
+ value = headers["retry-after"]
85
+ value&.to_i
86
+ end
87
+ end
88
+
89
+ # Buttondown's machine-readable error codes, for the cases where the code is
90
+ # more specific than the status. Consulted BEFORE the status, so a suppressed
91
+ # subscriber classifies correctly whichever status carries it.
92
+ ERROR_CODES = {
93
+ "subscriber_suppressed" => SubscriberSuppressedError,
94
+ "email_already_exists" => EmailAlreadyExistsError,
95
+ "subscriber_blocked" => SubscriberBlockedError,
96
+ "feature_disabled" => FeatureDisabledError
97
+ }.freeze
98
+
99
+ STATUS_ERRORS = {
100
+ 400 => BadRequestError,
101
+ 401 => AuthenticationError,
102
+ 403 => ForbiddenError,
103
+ 404 => NotFoundError,
104
+ 422 => UnprocessableEntityError,
105
+ 429 => RateLimitError
106
+ }.freeze
107
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Buttondown
4
+ # A thin, read-only view of the subscriber JSON Buttondown returns.
5
+ #
6
+ # Fields without a reader are still reachable through #[] and #to_h, so a new
7
+ # API field doesn't need a gem release.
8
+ class Subscriber
9
+ # Types from which a subscriber never receives another email.
10
+ TERMINAL_TYPES = %w[unsubscribed blocked complained undeliverable].freeze
11
+
12
+ def initialize(attributes = {})
13
+ @attributes = attributes || {}
14
+ end
15
+
16
+ def id
17
+ @attributes["id"]
18
+ end
19
+
20
+ def email_address
21
+ @attributes["email_address"]
22
+ end
23
+
24
+ def type
25
+ @attributes["type"]
26
+ end
27
+
28
+ # True when this subscriber will actually receive emails.
29
+ def regular?
30
+ type == "regular"
31
+ end
32
+
33
+ # Created, but hasn't confirmed through Buttondown's double opt-in yet.
34
+ def unactivated?
35
+ type == "unactivated"
36
+ end
37
+
38
+ # Opted out, bounced or complained. Never mail them again.
39
+ def terminal?
40
+ TERMINAL_TYPES.include?(type)
41
+ end
42
+
43
+ def [](key)
44
+ @attributes[key.to_s]
45
+ end
46
+
47
+ def to_h
48
+ @attributes.dup
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Buttondown
4
+ VERSION = "0.1.1"
5
+ end
data/lib/buttondown.rb ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "net/http"
5
+ # Explicit: Client::CONNECTION_ERRORS names OpenSSL::SSL::SSLError at class-body
6
+ # evaluation time, and net/http only loads openssl lazily.
7
+ require "openssl"
8
+ require "uri"
9
+
10
+ require_relative "buttondown/version"
11
+ require_relative "buttondown/errors"
12
+ require_relative "buttondown/subscriber"
13
+ require_relative "buttondown/client"
14
+
15
+ module Buttondown
16
+ end
metadata ADDED
@@ -0,0 +1,59 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: buttondown
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - Nick Kelly
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: A Ruby client for the Buttondown newsletter API.
13
+ email:
14
+ - nick@fromthekeyboard.com
15
+ executables: []
16
+ extensions: []
17
+ extra_rdoc_files: []
18
+ files:
19
+ - ".rubocop.yml"
20
+ - ".undercover"
21
+ - CHANGELOG.md
22
+ - Gemfile
23
+ - Guardfile
24
+ - LICENSE.txt
25
+ - README.md
26
+ - Rakefile
27
+ - buttondown.gemspec
28
+ - lib/buttondown.rb
29
+ - lib/buttondown/client.rb
30
+ - lib/buttondown/errors.rb
31
+ - lib/buttondown/subscriber.rb
32
+ - lib/buttondown/version.rb
33
+ homepage: https://github.com/nickhammond/buttondown
34
+ licenses:
35
+ - MIT
36
+ metadata:
37
+ homepage_uri: https://github.com/nickhammond/buttondown
38
+ source_code_uri: https://github.com/nickhammond/buttondown
39
+ changelog_uri: https://github.com/nickhammond/buttondown/blob/main/CHANGELOG.md
40
+ bug_tracker_uri: https://github.com/nickhammond/buttondown/issues
41
+ rubygems_mfa_required: 'true'
42
+ rdoc_options: []
43
+ require_paths:
44
+ - lib
45
+ required_ruby_version: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: 3.3.0
50
+ required_rubygems_version: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ requirements: []
56
+ rubygems_version: 4.0.16
57
+ specification_version: 4
58
+ summary: Ruby client for the Buttondown newsletter API
59
+ test_files: []