Sha256: 96bf3d8a55762da6b6bbf97d10f57e5adeed16146ffe4eb3c829a160333049fd

Contents?: true

Size: 1.51 KB

Versions: 4

Compression:

Stored size: 1.51 KB

Contents

module ShopifyApp
  class ScripttagsManager
    class CreationFailed < StandardError; end

    def self.queue(shop_domain, shop_token, scripttags)
      ShopifyApp::ScripttagsManagerJob.perform_later(
        shop_domain: shop_domain,
        shop_token: shop_token,
        scripttags: scripttags
      )
    end

    attr_reader :required_scripttags

    def initialize(scripttags)
      @required_scripttags = scripttags
    end

    def recreate_scripttags!
      destroy_scripttags
      create_scripttags
    end

    def create_scripttags
      return unless required_scripttags.present?

      required_scripttags.each do |scripttag|
        create_scripttag(scripttag) unless scripttag_exists?(scripttag[:src])
      end
    end

    def destroy_scripttags
      ShopifyAPI::ScriptTag.all.each do |scripttag|
        ShopifyAPI::ScriptTag.delete(scripttag.id) if is_required_scripttag?(scripttag)
      end

      @current_scripttags = nil
    end

    private

    def is_required_scripttag?(scripttag)
      required_scripttags.map{ |w| w[:src] }.include? scripttag.src
    end

    def create_scripttag(attributes)
      attributes.reverse_merge!(format: 'json')
      scripttag = ShopifyAPI::ScriptTag.create(attributes)
      raise CreationFailed, scripttag.errors.full_messages.to_sentence unless scripttag.persisted?
      scripttag
    end

    def scripttag_exists?(src)
      current_scripttags[src]
    end

    def current_scripttags
      @current_scripttags ||= ShopifyAPI::ScriptTag.all.index_by(&:src)
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
shopify_app-7.2.0 lib/shopify_app/scripttags_manager.rb
shopify_app-7.1.1 lib/shopify_app/scripttags_manager.rb
shopify_app-7.1.0 lib/shopify_app/scripttags_manager.rb
shopify_app-7.0.11 lib/shopify_app/scripttags_manager.rb