Class: ZeroDrop::Client
- Inherits:
-
Object
- Object
- ZeroDrop::Client
- Defined in:
- lib/zerodrop.rb
Overview
The ZeroDrop API client.
Instance Method Summary collapse
-
#fetch_latest(inbox, filter: nil) ⇒ ZeroDrop::Email?
Returns the newest email matching the filter, or nil.
-
#generate_inbox ⇒ String
Returns a ready-to-use email address instantly.
-
#initialize(api_key: nil, base_url: DEFAULT_BASE_URL) ⇒ Client
constructor
A new instance of Client.
-
#wait_for_latest(inbox, timeout: 10, poll_interval: 2, filter: nil) ⇒ ZeroDrop::Email
Blocks until an email matching the filter arrives.
Constructor Details
#initialize(api_key: nil, base_url: DEFAULT_BASE_URL) ⇒ Client
Returns a new instance of Client.
79 80 81 82 |
# File 'lib/zerodrop.rb', line 79 def initialize(api_key: nil, base_url: DEFAULT_BASE_URL) @api_key = api_key @base_url = base_url.chomp("/") end |
Instance Method Details
#fetch_latest(inbox, filter: nil) ⇒ ZeroDrop::Email?
Returns the newest email matching the filter, or nil.
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 |
# File 'lib/zerodrop.rb', line 99 def fetch_latest(inbox, filter: nil) name = inbox_name(inbox) uri = URI("#{@base_url}/api/inbox/#{name}?source=ruby-sdk") res = http_get(uri) raise AuthError if res.code == "401" raise NetworkError, "API returned #{res.code}" unless res.code == "200" payload = JSON.parse(res.body) emails = payload.fetch("emails", []) emails.each do |raw| email = build_email(raw) return email if filter.nil? || filter.matches?(email) end nil rescue JSON::ParserError => e raise NetworkError, "invalid response: #{e.}" rescue Errno::ECONNREFUSED, Errno::ETIMEDOUT, SocketError => e raise NetworkError, "#{e.} (check https://zerodrop.instatus.com)" end |
#generate_inbox ⇒ String
Returns a ready-to-use email address instantly. No network request is made.
88 89 90 91 92 |
# File 'lib/zerodrop.rb', line 88 def generate_inbox adjective = ADJECTIVES.sample suffix = SecureRandom.alphanumeric(7).downcase "#{adjective}-#{suffix}@#{FREE_DOMAIN}" end |
#wait_for_latest(inbox, timeout: 10, poll_interval: 2, filter: nil) ⇒ ZeroDrop::Email
Blocks until an email matching the filter arrives.
Polls every poll_interval seconds up to timeout seconds.
130 131 132 133 134 135 136 137 138 139 140 141 |
# File 'lib/zerodrop.rb', line 130 def wait_for_latest(inbox, timeout: 10, poll_interval: 2, filter: nil) deadline = Time.now + timeout loop do email = fetch_latest(inbox, filter: filter) return email if email raise TimeoutError.new(inbox, timeout) if Time.now + poll_interval > deadline sleep poll_interval end end |