Sha256: 8781c67b6155e19600d97df8038df8db588ea4e4b3ffb3123eb235f2618a87b5

Contents?: true

Size: 1.94 KB

Versions: 3

Compression:

Stored size: 1.94 KB

Contents

module LetterOpenerWeb
  class Letter
    cattr_accessor :letters_location do
      Rails.root.join("tmp", "letter_opener")
    end

    attr_reader :id, :sent_at

    def self.search
      letters = Dir.glob("#{letters_location}/*").map do |folder|
        new :id => File.basename(folder), :sent_at => File.mtime(folder)
      end
      letters.sort_by(&:sent_at).reverse
    end

    def self.find(id)
      new id: id
    end

    def self.destroy_all
      FileUtils.rm_rf(letters_location)
    end

    def initialize(params)
      @id      = params.fetch(:id)
      @sent_at = params[:sent_at]
    end

    def plain_text
      @plain_text ||= adjust_link_targets read_file(:plain)
    end

    def rich_text
      @rich_text ||= adjust_link_targets read_file(:rich)
    end

    def to_param
      id
    end

    private

    def read_file(style)
      File.read("#{letters_location}/#{id}/#{style}.html")
    end

    def adjust_link_targets(contents)
      # We cannot feed the whole file to an XML parser as some mails are
      # "complete" (as in they have the whole <html> structure) and letter_opener
      # prepends some information about the mail being sent, making REXML
      # complain about it
      contents.scan(/<a[^>]+>(?:.|\s)*?<\/a>/).each do |link|
        fixed_link = fix_link_html(link)
        xml        = REXML::Document.new(fixed_link).root
        unless xml.attributes['href'] =~ /(plain|rich).html/
          xml.attributes['target'] = '_blank'
          contents.gsub!(link, xml.to_s)
        end
      end
      contents
    end

    def fix_link_html(link_html)
      # REFACTOR: we need a better way of fixing the link inner html
      link_html.dup.tap do |fixed_link|
        fixed_link.gsub!('<br>', '<br/>')
        fixed_link.scan(/<img(?:[^>]+?)>/).each do |img|
          fixed_img = img.dup
          fixed_img.gsub!(/>$/, '/>') unless img =~ /\/>$/
          fixed_link.gsub!(img, fixed_img)
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
letter_opener_web-1.0.0.rc3 app/models/letter_opener_web/letter.rb
letter_opener_web-1.0.0.rc2 app/models/letter_opener_web/letter.rb
letter_opener_web-1.0.0.rc1 app/models/letter_opener_web/letter.rb