Sha256: a85a355795728cf34d2f13573d522f4281cbd98a5966e7f464d15a4bd25c4a84

Contents?: true

Size: 1.54 KB

Versions: 10

Compression:

Stored size: 1.54 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 find_one
        result = super
        update_parent(result) if result
      end

      def find_some
        result = super
        update_parent(result) if result.any?
        result
      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.param_key}_id").to_sym
        end

        def fetch
          fetch_embedded || super
        end

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

        def embedded_params
          @embedded_params ||= parent.attributes.to_params[name]
        end

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

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
spyke-1.8.5 lib/spyke/associations/association.rb
spyke-1.8.4 lib/spyke/associations/association.rb
spyke-1.8.3 lib/spyke/associations/association.rb
spyke-1.8.2 lib/spyke/associations/association.rb
spyke-1.8.1 lib/spyke/associations/association.rb
spyke-1.8.0 lib/spyke/associations/association.rb
spyke-1.7.2 lib/spyke/associations/association.rb
spyke-1.7.1 lib/spyke/associations/association.rb
spyke-1.7.0 lib/spyke/associations/association.rb
spyke-1.6.0 lib/spyke/associations/association.rb