Sha256: 5695e6cfd7c0a56be5492056726ea17870ff5de47b90e4f150ec740bda085d72

Contents?: true

Size: 1.83 KB

Versions: 19

Compression:

Stored size: 1.83 KB

Contents

module Graphiti
  module Util
    class Link
      def initialize(sideload, model)
        @sideload = sideload
        @model = model
        @linkable = true

        if @sideload.type == :polymorphic_belongs_to
          if (type = @model.send(@sideload.grouper.field_name))
            @sideload = @sideload.children.values.find { |c|
              c.group_name == type.to_sym
            }
            @polymorphic_sideload_not_found = true unless @sideload
          else
            @linkable = false
          end
        end
      end

      def generate
        if linkable?
          on_demand_links(raw_url)
        end
      end

      private

      def linkable?
        return false if @polymorphic_sideload_not_found

        if @sideload.type == :belongs_to
          !@model.send(@sideload.foreign_key).nil?
        else
          @linkable
        end
      end

      def raw_url
        if @sideload.link_proc
          @sideload.link_proc.call(@model)
        elsif params.empty?
          path
        else
          "#{path}?#{CGI.unescape(params.to_query)}"
        end
      end

      def on_demand_links(url)
        return url unless Graphiti.config.links_on_demand

        url << if url.include?("?")
          "&links=true"
        else
          "?links=true"
        end
        url
      end

      def params
        @params ||= {}.tap do |params|
          if @sideload.type != :belongs_to || @sideload.remote?
            params[:filter] = @sideload.base_filter([@model])
          end

          @sideload.params_proc&.call(params, [@model])
        end
      end

      def path
        @path ||=
          path = @sideload.resource.endpoint[:url].to_s
        if @sideload.type == :belongs_to && !@sideload.remote?
          path = "#{path}/#{@model.send(@sideload.foreign_key)}"
        end
        path
      end
    end
  end
end

Version data entries

19 entries across 19 versions & 1 rubygems

Version Path
graphiti-1.2.16 lib/graphiti/util/link.rb
graphiti-1.2.15 lib/graphiti/util/link.rb
graphiti-1.2.14 lib/graphiti/util/link.rb
graphiti-1.2.13 lib/graphiti/util/link.rb
graphiti-1.2.12 lib/graphiti/util/link.rb
graphiti-1.2.11 lib/graphiti/util/link.rb
graphiti-1.2.10 lib/graphiti/util/link.rb
graphiti-1.2.9 lib/graphiti/util/link.rb
graphiti-1.2.8 lib/graphiti/util/link.rb
graphiti-1.2.7 lib/graphiti/util/link.rb
graphiti-1.2.6 lib/graphiti/util/link.rb
graphiti-1.2.5 lib/graphiti/util/link.rb
graphiti-1.2.4 lib/graphiti/util/link.rb
graphiti-1.2.3 lib/graphiti/util/link.rb
graphiti-1.2.2 lib/graphiti/util/link.rb
graphiti-1.2.1 lib/graphiti/util/link.rb
graphiti-1.2.0 lib/graphiti/util/link.rb
graphiti-1.1.1 lib/graphiti/util/link.rb
graphiti-1.1.0 lib/graphiti/util/link.rb