Sha256: 49f8dea1434e356be67162c32987942484d749da3b86443982f2f2c2cbce5c9e

Contents?: true

Size: 1.25 KB

Versions: 15

Compression:

Stored size: 1.25 KB

Contents

require 'spyke/relation'
require 'spyke/result'

module Spyke
  module Associations
    class Association < Relation
      attr_reader :parent, :name

      def initialize(klass, parent, name, options = {})
        super(klass, options)
        @parent, @name = parent, name
      end

      def load
        find_one # Override for plural associations that return an association object
      end

      def assign_nested_attributes(attributes)
        update_parent new(attributes)
      end

      def create(attributes = {})
        add_to_parent super
      end

      def new(*args)
        add_to_parent super
      end

      alias :build :new

      private

        def add_to_parent(record)
          update_parent record
        end

        def foreign_key
          (@options[:foreign_key] || "#{parent.class.model_name.element}_id").to_sym
        end

        def fetch
          fetch_embedded || super
        end

        def fetch_embedded
          if embedded
            Result.new(data: embedded)
          elsif !uri
            Result.new(data: nil)
          end
        end

        def embedded
          parent.attributes[name]
        end

        def update_parent(value)
          parent.attributes[name] = value
        end
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
spyke-5.2.0 lib/spyke/associations/association.rb
spyke-5.1.0 lib/spyke/associations/association.rb
spyke-5.0.0 lib/spyke/associations/association.rb
spyke-4.1.1 lib/spyke/associations/association.rb
spyke-4.1.0 lib/spyke/associations/association.rb
spyke-4.0.1 lib/spyke/associations/association.rb
spyke-4.0.0 lib/spyke/associations/association.rb
spyke-3.1.5 lib/spyke/associations/association.rb
spyke-3.1.4 lib/spyke/associations/association.rb
spyke-3.1.3 lib/spyke/associations/association.rb
spyke-3.1.2 lib/spyke/associations/association.rb
spyke-3.1.1 lib/spyke/associations/association.rb
spyke-3.1.0 lib/spyke/associations/association.rb
spyke-3.0.0 lib/spyke/associations/association.rb
spyke-2.0.1 lib/spyke/associations/association.rb