Skip to content

Instantly share code, notes, and snippets.

@abevoelker
Last active August 7, 2018 18:36
Show Gist options
  • Save abevoelker/a8742dffec7d62dca01405c3466a91b2 to your computer and use it in GitHub Desktop.
Save abevoelker/a8742dffec7d62dca01405c3466a91b2 to your computer and use it in GitHub Desktop.
OneSignal Ruby notifications
require "typhoeus"
class OneSignal
class << self
[:app_id, :api_key, :timeout, :connecttimeout].each do |opt|
define_method(:"#{opt}=") {|val| instance_variable_set(:"@#{opt}", val)}
define_method(opt) { begin; instance_variable_get(:"@#{opt}"); rescue NameError; nil; end }
end
end
def self.configure
yield self
end
class TimeoutError < StandardError; end
class NoHTTPResponseError < StandardError; end
class NonSuccessfulHTTPError < StandardError; end
class Notification
def self.create(params)
app_id = params.delete(:app_id) || self.parent.app_id
raise "OneSignal App ID is required" unless app_id
api_key = params.delete(:api_key) || self.parent.api_key
raise "OneSignal API key is required" unless api_key
Typhoeus.post(
"https://onesignal.com/api/v1/notifications",
timeout: self.parent.timeout || 15,
connecttimeout: self.parent.connecttimeout || 15,
followlocation: true,
headers: {
"Content-Type" => "application/json; charset=utf-8",
"Authorization" => "Basic #{api_key}",
},
body: { app_id: app_id }.merge(params).as_json.to_json,
).tap do |response|
if response.timed_out?
raise TimeoutError, response.inspect
elsif response.code == 0
raise NoHTTPResponseError, response.inspect
elsif !response.success?
raise NonSuccessfulHTTPError, response.inspect
end
end
end
end
end
# Usage:
#
# OneSignal.configure do |config|
# config.app_id = ENV.fetch("ONESIGNAL_APP_ID")
# config.api_key = ENV.fetch("ONESIGNAL_API_KEY")
# end
#
# OneSignal::Notification.create(
# headings: { en: "MyApp" },
# contents: { en: "foo bar baz" },
# ios_badgeType: "Increase",
# ios_badgeCount: 1,
# filters: [
# { field: "tag", key: "user_id", relation: "=", value: 123 },
# ],
# )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment