Skip to content

Commit

Permalink
Step 7 - Add Chuck API + publish joke to Ably over REST
Browse files Browse the repository at this point in the history
  • Loading branch information
mattheworiordan committed Feb 3, 2017
1 parent fcab8df commit 7e00403
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion app/controllers/webhook_controller.rb
Expand Up @@ -12,12 +12,39 @@ def chuck_request
Array(item.dig('data', 'messages')).each do |message_raw|
# Use Ably to parse messages from JSON so that all encoding issues are resolved automatically
message = Ably::Models::Message.from_json(message_raw)
puts "Received Message with data '#{message.data}'"
if message.data.strip.empty?
get_random_joke
else
find_matching_jokes message.data
end
end
end
render json: { "success": true }
else
render json: { "error": "items Array attribute missing from body" }, status: :unprocessable_entity
end
end

private
def get_random_joke
chuck_request_started = Time.now.to_f
response = JSON.parse(HTTP.get('https://api.chucknorris.io/jokes/random').to_s)
publish_joke response['value'], Time.now.to_f - chuck_request_started
end

def find_matching_jokes(text)
chuck_request_started = Time.now.to_f
response = JSON.parse(HTTP.get("https://api.chucknorris.io/jokes/search?query=#{CGI::escape(text)}").to_s)
if response['result']
response['result'].first(3).each do |joke|
publish_joke joke['value'], Time.now.to_f - chuck_request_started
end
else
publish_joke "No Chuck joke matching text '#{text}'", Time.now.to_f - chuck_request_started
end
end

def publish_joke(joke, chuck_time)
ably_rest.channels.get('chuck:jokes').publish('joke', { joke: joke, chuckTime: (chuck_time * 1000).to_i })
end
end

0 comments on commit 7e00403

Please sign in to comment.