Sha256: 46e33bfb22f887dff1cc08dbf34533c35bff7827b4c0e5ca1dbf6599abd64490

Contents?: true

Size: 1.3 KB

Versions: 7

Compression:

Stored size: 1.3 KB

Contents

# frozen_string_literal: true

module PagesCore
  class ImageEmbedder
    include ActionView::Helpers::AssetTagHelper
    include PagesCore::ImagesHelper
    include Rails.application.routes.url_helpers

    def initialize(string)
      @string = string
    end

    def embed
      parse_images(@string)
    end

    private

    def image_expression
      /\[image:(\d+)([^\]]*)?\]/
    end

    def embed_image(id, size:, class_name:, link:)
      image_figure(
        Image.find(id).localize(I18n.locale),
        size: size, class_name: class_name, link: link
      )
    rescue ActiveRecord::RecordNotFound
      nil
    end

    def embed_image_size(str)
      if str =~ /size="(\d*x\d*)"/
        Regexp.last_match(1)
      else
        default_image_size
      end
    end

    def parse_image(str)
      id = str.match(image_expression)[1]
      options = str.match(image_expression)[2]
      class_name = (Regexp.last_match(1) if options =~ /class="([\s\-\w]+)"/)
      link = (Regexp.last_match(1) if options =~ /link="([^"]+)"/)
      embed_image(id,
                  size: embed_image_size(options),
                  class_name: class_name,
                  link: link)
    end

    def parse_images(string)
      string.gsub(image_expression).each do |str|
        parse_image(str)
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
pages_core-3.12.7 app/formatters/pages_core/image_embedder.rb
pages_core-3.12.6 app/formatters/pages_core/image_embedder.rb
pages_core-3.12.5 app/formatters/pages_core/image_embedder.rb
pages_core-3.12.4 app/formatters/pages_core/image_embedder.rb
pages_core-3.12.3 app/formatters/pages_core/image_embedder.rb
pages_core-3.12.2 app/formatters/pages_core/image_embedder.rb
pages_core-3.12.1 app/formatters/pages_core/image_embedder.rb