Sha256: e63e75bf8103cadf8ee6680b43a4cba06cae48d338bea7c0ec2711bac7f66595

Contents?: true

Size: 1.43 KB

Versions: 3

Compression:

Stored size: 1.43 KB

Contents

require 'nokogiri'

module ImproveTypography
  class Base < Struct.new(:str, :options)
    def self.call(*args)
      new(*args).call
    end

    def initialize(str, options = {})
      super(str, options)
    end

    def call
      doc.xpath('.//text()').each do |node|
        processor_classes.each do |processor|
          node.content = processor.call(node.content, options)
        end
      end

      CGI.unescapeHTML(
        doc.to_html.strip[5..-7]
      )
    end

    private

    def doc
      @doc ||= Nokogiri::HTML::DocumentFragment.parse("<div>#{str}</div>")
    end

    def configuration
      @configuration ||= Configuration.new
    end

    def processors
      options.fetch(:processors, configuration.processors)
    end

    def processor_classes
      @processor_classes ||= processors.map do |klass|
        processor_for_locale(klass)
      end
    end

    def all_processor_classes
      @all_processor_classes ||= ObjectSpace.each_object(Class).select { |klass| klass < Processor }
    end

    def processor_for_locale(klass)
      @processor_for_locale ||= {}
      @processor_for_locale[klass] ||= begin
        name = klass.to_s.split('::').last
        locale_specific_klass = "ImproveTypography::Processors::#{locale.to_s.upcase}::#{name}"
        all_processor_classes.detect { |cls| cls.to_s == locale_specific_klass } || klass
      end
    end

    def locale
      options.fetch(:locale, I18n.locale)
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
improve_typography-0.1.12 lib/improve_typography/base.rb
improve_typography-0.1.11 lib/improve_typography/base.rb
improve_typography-0.1.10 lib/improve_typography/base.rb