html_generator.rb 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. require 'date'
  2. require 'erb'
  3. module Fotos
  4. class HtmlGenerator
  5. MONTHS = %w(Styczeń Luty Marzec Kwiecień Maj Czerwiec Lipiec Sierpień Wrzesień Październik Listopad Grudzień)
  6. def initialize(options)
  7. @source_dir = Fotos::SourceDirectory.new(options[:source])
  8. @dest_dir = Fotos::SourceDirectory.new(options[:dest])
  9. @generate_thumbnails = options[:thumbnails]
  10. end
  11. attr_reader :source_dir, :dest_dir, :generate_thumbnails
  12. def call
  13. html_output = []
  14. html_output << render_template('header')
  15. html_output << render_period(@source_dir.dates)
  16. @source_dir.files_by_date.each do |date, assets|
  17. html_output << "<h2 id=\"#{date}\">#{date} <small><a href=\"#toc\">top</a></small></h2>"
  18. assets.reject(&:is_thumbnail?).each do |asset|
  19. ensure_thumbnail(asset)
  20. if File.exist?(asset.thumbnail_path(@dest_dir.path))
  21. html_output << "<a href=\"#{asset.path}\"><img src=\"#{asset.thumbnail_path}\" /></a>"
  22. else
  23. html_output << "<a href=\"#{asset.dirname}/#{asset.file_name}\"><img src=\"#{asset.path}\" /></a>"
  24. end
  25. end
  26. end
  27. html_output << render_template('footer')
  28. html_output.join("\n")
  29. end
  30. private
  31. def ensure_thumbnail(asset)
  32. return if File.exist?(asset.thumbnail_path(@dest_dir.path))
  33. if @generate_thumbnails
  34. begin
  35. Fotos::Thumbnail.new(asset).create(@dest_dir.path)
  36. rescue StandardError => e
  37. warn "Failed to create thumbnail for #{asset.file_name}: #{e.message}"
  38. end
  39. end
  40. end
  41. def render_period(dates)
  42. output = []
  43. dates.group_by(&:year).each do |year, y_dates|
  44. output << "<h2>#{year}</h2>"
  45. y_dates.group_by(&:month).each do |month, m_dates|
  46. month_name = MONTHS[month - 1]
  47. output << render_template('month', month: month_name, m_dates: m_dates)
  48. end
  49. end
  50. output.join("\n")
  51. end
  52. def render_template(name, context = {})
  53. path = Pathname.new(__FILE__).join('..', '..', '..', 'templates', "_#{name}.html.erb")
  54. template = ERB.new(File.read(path))
  55. template.result_with_hash(context)
  56. end
  57. end
  58. end