Sha256: 26a4af362dea3d158ae1549d670f8bcc08895285aaf7a03bef9e3e58d6f5f55a

Contents?: true

Size: 1.98 KB

Versions: 12

Compression:

Stored size: 1.98 KB

Contents

# frozen_string_literal: true

require 'open-uri'
require 'fileutils'
require 'aranha/parsers/source_address'
require 'eac_ruby_utils/fs/temp'

module Aranha
  module Parsers
    class Base
      class << self
        # @deprecated Use {#from_string} instead.
        # @param content [String]
        # @return [Aranha::Parsers::Base]
        def from_content(content)
          from_string(content)
        end

        # @param string [String]
        # @return [Aranha::Parsers::Base]
        def from_string(string)
          ::EacRubyUtils::Fs::Temp.on_file do |path|
            ::File.open(path.to_s, 'w:UTF-8') do |f|
              f.write string.dup.force_encoding('UTF-8')
            end
            r = new(path.to_path)
            r.content
            r
          end
        end
      end

      LOG_DIR_ENVVAR = 'ARANHA_PARSERS_LOG_DIR'

      attr_reader :source_address

      def initialize(url)
        @source_address = ::Aranha::Parsers::SourceAddress.new(url)
        log_content(source_address.serialize, '-source-address')
      end

      delegate :url, to: :source_address

      def content
        @content ||= log_content(source_address_content)
      end

      # @return [String]
      delegate :content, to: :source_address, prefix: true

      private

      # @return [String]
      def log_content(content, suffix = '')
        path = log_file(suffix)

        File.open(path, 'wb') { |file| file.write(content) } if path

        content
      end

      def log_file(suffix)
        dir = log_parsers_dir
        return nil unless dir

        f = ::File.join(dir, "#{self.class.name.parameterize}#{suffix}.log")
        FileUtils.mkdir_p(File.dirname(f))
        f
      end

      def log_parsers_dir
        return ENV[LOG_DIR_ENVVAR] if ENV[LOG_DIR_ENVVAR]
        return ::Rails.root.join('log', 'parsers') if rails_root_exist?

        nil
      end

      def rails_root_exist?
        ::Rails.root
        true
      rescue NameError
        false
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 2 rubygems

Version Path
aranha-parsers-0.21.0 lib/aranha/parsers/base.rb
aranha-parsers-0.20.0 lib/aranha/parsers/base.rb
eac_tools-0.69.1 sub/aranha-parsers/lib/aranha/parsers/base.rb
aranha-parsers-0.19.1 lib/aranha/parsers/base.rb
eac_tools-0.69.0 sub/aranha-parsers/lib/aranha/parsers/base.rb
eac_tools-0.68.0 sub/aranha-parsers/lib/aranha/parsers/base.rb
aranha-parsers-0.19.0 lib/aranha/parsers/base.rb
eac_tools-0.67.1 sub/aranha-parsers/lib/aranha/parsers/base.rb
eac_tools-0.67.0 sub/aranha-parsers/lib/aranha/parsers/base.rb
eac_tools-0.66.0 sub/aranha-parsers/lib/aranha/parsers/base.rb
eac_tools-0.65.1 sub/aranha-parsers/lib/aranha/parsers/base.rb
aranha-parsers-0.18.0 lib/aranha/parsers/base.rb