Sha256: 8f35b5d53daff3483d3928a5e80df07a5d5c9b1d74404f7d887af0480e9adf40

Contents?: true

Size: 1.61 KB

Versions: 18

Compression:

Stored size: 1.61 KB

Contents

module Superstore
  module BelongsTo
    extend ActiveSupport::Concern

    included do
      class_attribute :belongs_to_reflections
      self.belongs_to_reflections = {}
    end

    module ClassMethods
      # === Options
      # [:class_name]
      #   Use if the class cannot be inferred from the association
      # [:polymorphic]
      #   Specify if the association is polymorphic
      # Example:
      #   class Driver < Superstore::Base
      #   end
      #   class Truck < Superstore::Base
      #   end
      def belongs_to(name, options = {})
        Superstore::BelongsTo::Builder.build(self, name, options)
      end

      def generated_belongs_to_methods
        @generated_belongs_to_methods ||= begin
          mod = const_set(:GeneratedBelongsToMethods, Module.new)
          include mod
          mod
        end
      end
    end

    # Returns the belongs_to instance for the given name, instantiating it if it doesn't already exist
    def belongs_to_association(name)
      association = belongs_to_instance_get(name)

      if association.nil?
        association = Superstore::BelongsTo::Association.new(self, belongs_to_reflections[name])
        belongs_to_instance_set(name, association)
      end

      association
    end

    private
      def clear_belongs_to_cache
        belongs_to_cache.clear if persisted?
      end

      def belongs_to_cache
        @belongs_to_cache ||= {}
      end

      def belongs_to_instance_get(name)
        belongs_to_cache[name.to_sym]
      end

      def belongs_to_instance_set(name, association)
        belongs_to_cache[name.to_sym] = association
      end
  end
end

Version data entries

18 entries across 18 versions & 1 rubygems

Version Path
superstore-1.2.0 lib/superstore/belongs_to.rb
superstore-1.1.4 lib/superstore/belongs_to.rb
superstore-1.1.3 lib/superstore/belongs_to.rb
superstore-1.1.2 lib/superstore/belongs_to.rb
superstore-1.1.1 lib/superstore/belongs_to.rb
superstore-1.1.0 lib/superstore/belongs_to.rb
superstore-1.0.12 lib/superstore/belongs_to.rb
superstore-1.0.11 lib/superstore/belongs_to.rb
superstore-1.0.10 lib/superstore/belongs_to.rb
superstore-1.0.9 lib/superstore/belongs_to.rb
superstore-1.0.8 lib/superstore/belongs_to.rb
superstore-1.0.7 lib/superstore/belongs_to.rb
superstore-1.0.6 lib/superstore/belongs_to.rb
superstore-1.0.5 lib/superstore/belongs_to.rb
superstore-1.0.4 lib/superstore/belongs_to.rb
superstore-1.0.3 lib/superstore/belongs_to.rb
superstore-1.0.2 lib/superstore/belongs_to.rb
superstore-1.0.0 lib/superstore/belongs_to.rb