lib/capistrano-payload/payload.rb in capistrano-payload-0.1.0 vs lib/capistrano-payload/payload.rb in capistrano-payload-0.3.0
- old
+ new
@@ -1,42 +1,62 @@
-require 'rest-client'
-require 'multi_json'
-
module CapistranoPayload
- class DeliveryError < StandardError ; end
+ class ConfigurationError < StandardError ; end
+ class DeliveryError < StandardError ; end
class Payload
+ include CapistranoPayload::Format
+ include CapistranoPayload::Request
+
+ # Allowed actions
+ ACTIONS = ['deploy', 'rollback']
+
attr_reader :action
+ attr_reader :message
attr_reader :data
+ attr_reader :format
attr_reader :params
# Initialize a new Payload object
#
- # action - Deployment action (deploy, rollback)
- # data - Deployment parameters
- # params - Extra parameters to payload (api_key, etc.), default: {}
- # Could not contain 'capistrano' key. Will be removed if present.
+ # action - Deployment action (deploy, rollback)
+ # message - Deployment message (optional)
+ # data - Payload data
+ # format - Payload format (:json, :form). Default: json
+ # params - Extra parameters to payload (api_key, etc.), default: {}
+ # Could not contain 'capistrano' key. Will be removed if present.
+ # Should be a hash
#
- def initialize(action, data, params={})
- @action = action
- @data = data.merge(:action => action)
- @params = params
+ def initialize(action, message, data, format=:json, params={})
+ @action = action
+ @message = message.strip
+ @data = data.merge(:action => @action, :message => @message)
+ @format = format.to_sym
+ @params = params.kind_of?(Hash) ? params : {}
- # Check if we have 'capistrano' keys (string or symbolic)
+ unless ACTIONS.include?(@action)
+ raise ConfigurationError, "Invalid payload action: #{action}."
+ end
+
+ # Check if we have an invalid format
+ unless FORMATS.include?(@format)
+ raise ConfigurationError, "Invalid payload format: #{format}."
+ end
+
+ # Check if we have 'payload' keys (string or symbolic)
unless @params.empty?
- @params.delete(:capistrano)
- @params.delete('capistrano')
+ @params.delete(:payload)
+ @params.delete('payload')
end
end
# Performs payload delivery
#
# url - Target url
#
def deliver(url)
- payload = MultiJson.encode({:capistrano => @data}.merge(@params))
+ payload = self.send(FORMAT_METHODS[@format])
begin
- RestClient.post(url, payload, :content_type => :json)
+ request(:post, url, {:payload => payload}.merge(@params), format)
rescue Exception => ex
raise DeliveryError, ex.message
end
end
end