Sha256: 6721c4bae1680b0a6b19d56e96f0836160006dcd4bc4be3600285f278cf75693

Contents?: true

Size: 1.89 KB

Versions: 10

Compression:

Stored size: 1.89 KB

Contents

# frozen_string_literal: true

#
# Copyright (c) 2019-present, Blue Marble Payroll, LLC
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#

module Dbee
  module Dsl
    # This is really syntactic sugar built on top of Association.  It can handle two main
    # use-cases when declaring associations:
    # - parent: create an association to a parent model (foreign key is on immediate table)
    # - child: create an association to a child model (foreign key is on child table)
    class AssociationBuilder
      attr_reader :inflector

      def initialize(inflector)
        raise ArgumentError, 'inflector is required' unless inflector

        @inflector = inflector

        freeze
      end

      def parent_association(on_class_name, name, opts = {})
        reference_constraint = {
          name: opts[:foreign_key] || :id,
          parent: opts[:primary_key] || inflector.foreign_key(name)
        }

        association(on_class_name, name, opts, reference_constraint)
      end

      def child_association(on_class_name, name, opts = {})
        reference_constraint = {
          name: opts[:foreign_key] || inflector.foreign_key(on_class_name),
          parent: opts[:primary_key] || :id
        }

        association(on_class_name, name, opts, reference_constraint)
      end

      private

      def association(on_class_name, name, opts, reference_constraint)
        association_opts = {
          model: opts[:model],
          constraints: [reference_constraint] + make_constraints(opts)
        }

        Association.new(on_class_name, inflector, name, association_opts)
      end

      def make_constraints(opts = {})
        array(opts[:constraints]) + array(opts[:static]).map { |c| c.merge(type: :static) }
      end

      def array(value)
        value.is_a?(Hash) ? [value] : Array(value)
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
dbee-3.1.0 lib/dbee/dsl/association_builder.rb
dbee-3.0.0 lib/dbee/dsl/association_builder.rb
dbee-2.1.1 lib/dbee/dsl/association_builder.rb
dbee-2.1.0 lib/dbee/dsl/association_builder.rb
dbee-2.1.0.pre.alpha lib/dbee/dsl/association_builder.rb
dbee-2.0.3 lib/dbee/dsl/association_builder.rb
dbee-2.0.2 lib/dbee/dsl/association_builder.rb
dbee-2.0.1 lib/dbee/dsl/association_builder.rb
dbee-2.0.0 lib/dbee/dsl/association_builder.rb
dbee-2.0.0.pre.alpha lib/dbee/dsl/association_builder.rb