Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tatey
Forked from coop/after.rb
Created August 21, 2012 10:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tatey/3414512 to your computer and use it in GitHub Desktop.
Save tatey/3414512 to your computer and use it in GitHub Desktop.
module Publishers
class HTTP
attr_accessor :key
attr_reader :hosts
def initialize attributes = nil
attributes ||= {}
self.event = attributes[:event]
self.hosts = attributes.fetch(:hosts) do
Rails.application.config.hosts
end
end
def publishers
{'http' => NonSSL, 'https' => SSL}
end
def publisher_for uri
publisher = publishers.fetch uri.split('//').first, 'http'
publisher.new uri
end
def publish payload
hosts.each { |uri| publisher_for(uri).publish payload }
end
def hosts= hosts
@hosts = hosts.map { |label, url| URI(url + '/api/private/receive') }
end
class NonSSL
attr_accessor :uri
def initialize uri
self.uri = uri
end
def http
@http ||= Net::HTTP.new uri.host, uri.port
end
def publish payload
request.set_form_data payload
http.request request
rescue Exception => e
Rails.logger.info "Couldn't send payload to #{uri}."
end
def request data
@request ||= Net::HTTP::Post.new uri.request_uri
end
def uri= uri
@uri = URI uri
end
end
class SSL < NonSSL
def http
@http ||= begin
http = Net::HTTP.new uri.host, uri.port
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http
end
end
end
end
module Publisheres
class HTTP
attr_accessor :key
attr_reader :hosts
def initialize attributes = nil
attributes ||= {}
self.event = attributes[:event]
self.hosts = attributes.fetch(:hosts) { Preferences.hosts }
end
def publish payload
hosts.each do |uri|
begin
http = Net::HTTP.new uri.host, uri.port
if uri.scheme == 'https'
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
request = Net::HTTP::Post.new uri.request_uri
request.set_form_data :payload => payload
http.request request
rescue Exception => e
Rails.logger.info "Couldn't send payload to #{uri}."
end
end
end
def hosts= hosts
@hosts = [].tap do |array|
hosts.each do |label, url|
array << URI(url + '/api/private/receive')
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment