feat: add logging and refactor image attachment

- Add logging to track the generation of weather art for each city.
- Refactor image attachment process to streamline the code by removing the
  separate method for attaching images.
- Ensure proper handling of the temporary file used for image processing.

These changes improve observability during the weather art generation
process and encapsulate the image attachment logic within the primary
method, reducing the overhead of a method call. The adjustments also
ensure that temporary files are managed correctly to prevent resource
leaks.
This commit is contained in:
songtianlun 2025-01-24 00:23:09 +08:00
parent b05cf10017
commit b4af78aa77
2 changed files with 15 additions and 12 deletions

View File

@ -12,6 +12,7 @@ class BatchGenerateWeatherArtsWorker
cities_to_process.each do |city| cities_to_process.each do |city|
break if Time.current - start_time > MAX_DURATION break if Time.current - start_time > MAX_DURATION
Rails.logger.info "Generating weather art for #{city.name}"
GenerateWeatherArtWorker.perform_async(city.id) GenerateWeatherArtWorker.perform_async(city.id)
sleep SLEEP_DURATION sleep SLEEP_DURATION

View File

@ -36,6 +36,8 @@ class GenerateWeatherArtWorker
end end
def create_weather_art(weather_data, prompt, image_url) def create_weather_art(weather_data, prompt, image_url)
tempfile = nil
ActiveRecord::Base.transaction do ActiveRecord::Base.transaction do
weather_art = city.weather_arts.create!( weather_art = city.weather_arts.create!(
weather_date: Date.today, weather_date: Date.today,
@ -43,21 +45,21 @@ class GenerateWeatherArtWorker
**weather_data **weather_data
) )
attach_image(weather_art, image_url) tempfile = Down.download(image_url)
weather_art.image.attach(
io: File.open(tempfile.path),
filename: generate_filename,
content_type: 'image/png'
)
weather_art weather_art
end end
end
def attach_image(weather_art, image_url)
tempfile = Down.download(image_url)
weather_art.image.attach(
io: tempfile,
filename: generate_filename,
content_type: "image/png"
)
ensure ensure
tempfile&.close if tempfile
tempfile&.unlink tempfile.close
tempfile.unlink
end
end end
def generate_filename def generate_filename