Sha256: 186da3f2dac2ad611e99706118080019400c8cc19d220db4e5b3f8460f698296

Contents?: true

Size: 1.73 KB

Versions: 3

Compression:

Stored size: 1.73 KB

Contents

require 'rom/sql/association'

module ROM
  module SQL
    class Schema < ROM::Schema
      class AssociationsDSL < BasicObject
        attr_reader :source, :registry

        def initialize(source, &block)
          @source = source
          @registry = {}
          instance_exec(&block)
        end

        def one_to_many(target, options = {})
          if options[:through]
            many_to_many(target, options)
          else
            add(Association::OneToMany.new(source, target, options))
          end
        end
        alias_method :has_many, :one_to_many

        def one_to_one(target, options = {})
          if options[:through]
            one_to_one_through(target, options)
          else
            add(Association::OneToOne.new(source, target, options))
          end
        end

        def one_to_one_through(target, options = {})
          add(Association::OneToOneThrough.new(source, target, options))
        end

        def many_to_many(target, options = {})
          add(Association::ManyToMany.new(source, target, options))
        end

        def many_to_one(target, options = {})
          add(Association::ManyToOne.new(source, target, options))
        end

        def belongs_to(name, options = {})
          many_to_one(dataset_name(name), options.merge(as: options[:as] || name))
        end

        def has_one(name, options = {})
          one_to_one(dataset_name(name), options.merge(as: options[:as] || name))
        end

        def call
          AssociationSet.new(registry)
        end

        private

        def add(association)
          registry[association.name] = association
        end

        def dataset_name(name)
          Inflector.pluralize(name).to_sym
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rom-sql-0.9.1 lib/rom/sql/schema/associations_dsl.rb
rom-sql-0.9.0 lib/rom/sql/schema/associations_dsl.rb
rom-sql-0.8.0 lib/rom/sql/schema/associations_dsl.rb