Class: TyreshopperSqs2cb::MessageHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/tyreshopper_sqs2cb.rb

Instance Method Summary collapse

Constructor Details

#initializeMessageHandler

Returns a new instance of MessageHandler.



12
13
14
15
16
17
18
19
20
21
# File 'lib/tyreshopper_sqs2cb.rb', line 12

def initialize

  logfile = ENV['TYRESHOPPER_SQS2CB_LOGFILE_PATH'].nil? ? STDOUT : File.open(ENV['TYRESHOPPER_SQS2CB_LOGFILE_PATH'], 'a')
  logfile.sync = true
  @logger = Logger.new logfile


  @sqs2cb = ::Sqs2cb::MessageHandler.new

end

Instance Method Details

#handle_received_message(message, options) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/tyreshopper_sqs2cb.rb', line 33

def handle_received_message(message, options)
  @options = options
  @logger.info "Tyreshopper Message received."
  @logger.debug message.body
  @logger.info "Sending..."

  @caseBlocksAPIEndpoint = options[:case_blocks_api_endpoint]
  @caseBlocksAPIToken = options[:caseblocks_api_token]

  send_to_caseblocks(JSON.parse(message.body))

rescue JSON::ParserError => ex
  # TODO needs some form of remote notification that an error occured.
  @logger.error "Bad message format. Unable to deserialize message into JSON."
  @logger.error ex
rescue Exception => ex
  @logger.error "Something caused a message handling failure."
  @logger.error ex
end

#send_to_caseblocks(msgHash) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/tyreshopper_sqs2cb.rb', line 54

def send_to_caseblocks(msgHash)
  @logger.info "Sending to CaseBlocks"

  @logger.info "Sending order #{msgHash["case"]["title"]} to caseblocks..."

  @logger.info "Looking for customer..."
  customer = find_or_create_customer(msgHash)

  msgHash["case"]["customer_ref"] = customer["customer_ref"]

  @logger.info "Creating order in caseblocks..."
  response = post("/case_blocks/tyre_shopper_orders", msgHash)

  @logger.info "Done."
  @logger.info "Received #{response}"
rescue RestClient::ExceptionWithResponse => ex
  if ex.response.nil?
    @logger.error "Received a bad response (null) from CaseBlocks. Re-raising."
    raise ex
  else
    @logger.error "Received #{ex.response.code} bad response: #{ex.response.body}"
  end
end

#stopObject



23
24
25
# File 'lib/tyreshopper_sqs2cb.rb', line 23

def stop
  @sqs2cb.stop
end

#transfer_messagesObject



27
28
29
30
31
# File 'lib/tyreshopper_sqs2cb.rb', line 27

def transfer_messages
  @sqs2cb.transfer_messages do |message, options|
    handle_received_message(message, options)
  end
end