Sha256: 2073d918de75fb1b1e35eff7a0f86e3cc86b9b9b431ada2246b0cef0b73c629b

Contents?: true

Size: 1.32 KB

Versions: 12

Compression:

Stored size: 1.32 KB

Contents

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

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

      def initialize(parent, name, options = {})
        super (options[:class_name] || name.to_s).classify.constantize, 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)
        parent.attributes[name] = new(attributes).attributes
      end

      def create(attributes = {})
        add_to_parent super
      end

      def new(*args)
        add_to_parent super
      end

      def build(*args)
        new(*args)
      end

      private

        def add_to_parent(record)
          parent.attributes[name] = record.attributes
          record
        end

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

        def fetch
          fetch_embedded || super
        end

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

        def embedded_attributes
          parent.attributes[name]
        end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
spyke-1.5.0 lib/spyke/associations/association.rb
spyke-1.4.1 lib/spyke/associations/association.rb
spyke-1.4.0 lib/spyke/associations/association.rb
spyke-1.3.0 lib/spyke/associations/association.rb
spyke-1.2.1 lib/spyke/associations/association.rb
spyke-1.2.0 lib/spyke/associations/association.rb
spyke-1.1.2 lib/spyke/associations/association.rb
spyke-1.1.1 lib/spyke/associations/association.rb
spyke-1.1.0 lib/spyke/associations/association.rb
spyke-1.0.2 lib/spyke/associations/association.rb
spyke-1.0.1 lib/spyke/associations/association.rb
spyke-1.0.0 lib/spyke/associations/association.rb