Module: UrlReport
- Defined in:
- lib/url_report.rb,
lib/url_report/version.rb
Defined Under Namespace
Classes: Error
Constant Summary collapse
- VERSION =
"0.1.0"
Class Method Summary collapse
-
.generate(url) ⇒ Object
Main method to generate a PDF report from a URL.
Class Method Details
.generate(url) ⇒ Object
Main method to generate a PDF report from a URL
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
# File 'lib/url_report.rb', line 14 def self.generate(url) raise Error, "No URL provided" if url.nil? || url.strip.empty? # ----------------------------- # 1. Fetch the website # ----------------------------- response = HTTParty.get(url) raise Error, "Failed to fetch page: #{response.code}" if response.code != 200 # ----------------------------- # 2. Parse HTML with Nokogiri # ----------------------------- doc = Nokogiri::HTML(response.body) # Headings headings = doc.css('h1,h2').map(&:text).map(&:strip).reject(&:empty?) # Links links = doc.css("a").map { |a| [a.text.strip, a['href']] } links.reject! { |text, href| text.empty? || href.nil? } links = links.first(10) # Images images = doc.css('img').map { |img| img['src'] }.reject(&:nil?).first(5) images.map! { |src| URI.join(url, src).to_s rescue src } # ----------------------------- # 3. Generate PDF with Prawn # ----------------------------- = Time.now.strftime("%Y-%m-%d_%H-%M-%S") filename = "ruby_report_#{}.pdf" Prawn::Document.generate(filename) do text "Ruby Report", size: 20, style: :bold, align: :center move_down 20 text "Source: #{url}", size: 10, align: :right text "Date: #{Date.today}", size: 10, align: :right move_down 20 # Headings unless headings.empty? text "Headings Found:", style: :bold headings.each_with_index do |h, i| safe_text = h.encode('Windows-1252', invalid: :replace, undef: :replace, replace: '?') text "#{i+1}. #{safe_text}", size: 12 end move_down 15 end # Links unless links.empty? text "Links Found:", style: :bold links.each_with_index do |(text, href), i| safe_text = text.encode('Windows-1252', invalid: :replace, undef: :replace, replace: '?') text "#{i+1}. #{safe_text}", size: 12, leading: 2 text "<link href='#{href}'>#{href}</link>", inline_format: true, size: 9, color: "0000FF" move_down 10 end move_down 15 end # Images unless images.empty? text "Images Found:", style: :bold images.each_with_index do |img_url, i| text "#{i+1}. #{img_url}", size: 10, color: "0000AA" begin open(img_url) { |f| image f, fit: [400, 300] } rescue text "(Failed to load image)", size: 9, color: "FF0000" end move_down 5 end move_down 15 end text "Ruby Report powered by (HTTParty + Nokogiri + Prawn)", size: 9, align: :center, style: :italic end filename end |