Recently, I returned to Ruby on Rails, one of my favourite web application frameworks. This time, I aimed to build a simple management tool for scheduling website crawls—a key component of a side project I'm working on.
The tool's purpose is straightforward:
- Maintain a list of websites to crawl.
- Schedule crawls for these websites.
- Trigger a Golang process for the actual crawling task.
Adding an SQS Service in Rails
In Rails, services are often used to encapsulate business logic that doesn’t belong in the standard MVC structure. For my application, I created a services/sqs_send_service.rb
to handle sending messages to SQS queues.
require "aws-sdk-sqs"
class SqsSendService
# Client is a class method that returns an instance of the SQS client
# @return [Aws::SQS::Client] An instance of the SQS client
def self.client
@client ||= Aws::SQS::Client.new
end
# The initialize method sets the queue URL
# @param sqs_queue_url [String] The URL of the SQS queue
# @return [SqsSendService] An instance of the SqsSendService class
def initialize(sqs_queue_url = nil)
sqs_queue_url ||= ENV["SQS_QUEUE_URL"]
@queue_url = sqs_queue_url
end
# The send_message method sends a message to the SQS queue
# @param message_body [String] The body of the message
# @param message_attributes [Hash] The attributes of the message
# @return [Aws::SQS::Types::SendMessageResult] The result of the send message operation
def send_message(message_body, message_attributes = {})
self.client.send_message({
queue_url: @queue_url,
message_body: message_body,
message_attributes: message_attributes
})
end
end
- Reusable SQS Client: The client method ensures a single instance of the
Aws::SQS::Client
is reused, improving efficiency. - Dynamic Configuration: The queue URL can be set either via the
sqs_queue_url
parameter or an environment variable(ENV["SQS_QUEUE_URL"])
, making it flexible for different environments. - Message Attributes: The send_message method supports custom attributes, allowing for enhanced message context when sending data.
Why Use SQS?
- The Rails app handles scheduling and sends crawl requests via SQS.
- The Golang service listens to the SQS queue and processes the crawl jobs.
Final Thoughts
This project reminded me of why I enjoy working with Rails—its flexibility allows me to integrate tools like SQS seamlessly. By leveraging Rails services, I kept my application’s design clean and modular.
If you're looking to integrate AWS SQS into your Rails app, a service like the SqsSendService
provides a solid foundation. H
Comments
Post a Comment