Sha256: fbfa3a3c021323185767cf54b3e2e45840adce43e5a9b38cb0a7e600d229a448

Contents?: true

Size: 1.98 KB

Versions: 8

Compression:

Stored size: 1.98 KB

Contents

module Fontist
  class Formula
    def initialize(options = {})
      @font_name = options.fetch(:font_name, nil)

      check_and_register_font_formulas
    end

    def self.all
      new.all
    end

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

    def self.find_fonts(name)
      new(font_name: name).find_fonts
    end

    def all
      @all ||= Fontist::Registry.instance.formulas
    end

    def find
      [find_formula].flatten.first
    end

    def find_fonts
      formulas = [find_formula].flatten
      match_fonts_by_name(formulas) unless formulas.empty?
    end

    private

    attr_reader :font_name

    def find_formula
      find_by_font_name || find_by_font || []
    end

    def formulas
      @formulas ||= all.to_h
    end

    def match_fonts_by_name(formulas)
      matched_fonts = formulas.map do |formula|
        formula.fonts.select do |font|
          font.name.downcase == font_name.downcase
        end
      end

      matched_fonts.empty? ? nil : matched_fonts.flatten
    end

    def find_by_font_name
      matched_formulas = formulas.select do |key, value|
        !value.fonts.map(&:name).grep(/#{font_name}/i).empty?
      end

      matched_formulas.empty? ? nil : matched_formulas.values
    end

    # Note
    #
    # These interface recursively look into every single font styles,
    # so ideally try to avoid using it when possible, and that's why
    # we've added it as last option in formula finder.
    #
    def find_by_font
      matched_formulas = formulas.select do |key, value|
        match_in_font_styles?(value[:fonts])
      end

      matched_formulas.empty? ? nil : matched_formulas.values
    end

    def match_in_font_styles?(fonts)
      styles = fonts.select do |font|
        !font.styles.map(&:font).grep(/#{font_name}/i).empty?
      end

      styles.empty? ? false : true
    end

    def check_and_register_font_formulas
      $check_and_register_font_formulas ||= Fontist::Formulas.register_formulas
    end
  end
end

Version data entries

8 entries across 7 versions & 2 rubygems

Version Path
fontist-1.3.0 lib/fontist/formula.rb
fontist-1.2.1 lib/fontist/formula.rb
metanorma-cli-1.3.4 gems/ruby/2.6.0/gems/fontist-1.1.0/lib/fontist/formula.rb
metanorma-cli-1.3.4 gems/ruby/2.6.0/gems/fontist-1.2.0/lib/fontist/formula.rb
fontist-1.2.0 lib/fontist/formula.rb
metanorma-cli-1.3.3.1 gems/ruby/2.6.0/gems/fontist-1.1.0/lib/fontist/formula.rb
fontist-1.1.0 lib/fontist/formula.rb
fontist-1.0.0 lib/fontist/formula.rb