Sha256: dc01c0be1d90f5ef048db4460f5cd10041a26db1178724ac2926c13f38809ec0

Contents?: true

Size: 1.2 KB

Versions: 32

Compression:

Stored size: 1.2 KB

Contents

module Spyke
  module Associations
    class Builder
      def initialize(parent_class, name, type, options = {})
        @parent_class, @name, @type, @options = parent_class, name, type, options
      end

      def build(parent)
        @type.new(klass, parent, @name, @options)
      end

      def klass
        @klass ||= custom_class || compute_class(@name)
      end

      private

        def custom_class
          @options[:class_name].constantize if @options[:class_name]
        end

        # https://github.com/rails/rails/blob/70ac072976c8cc6f013f0df3777e54ccae3f4f8c/activerecord/lib/active_record/inheritance.rb#L132-L150
        def compute_class(type_name)
          parent_name = @parent_class.to_s
          type_name = type_name.to_s.classify

          candidates = []
          parent_name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" }
          candidates << type_name

          candidates.each do |candidate|
            constant = ActiveSupport::Dependencies.safe_constantize(candidate)
            return constant if candidate == constant.to_s
          end
          raise NameError.new("uninitialized constant #{candidates.first}", candidates.first)
        end
    end
  end
end

Version data entries

32 entries across 32 versions & 1 rubygems

Version Path
spyke-6.1.0 lib/spyke/associations/builder.rb
spyke-6.0.0 lib/spyke/associations/builder.rb
spyke-5.4.3 lib/spyke/associations/builder.rb
spyke-5.4.2 lib/spyke/associations/builder.rb
spyke-5.4.1 lib/spyke/associations/builder.rb
spyke-5.4.0 lib/spyke/associations/builder.rb
spyke-5.3.4 lib/spyke/associations/builder.rb
spyke-5.3.3 lib/spyke/associations/builder.rb
spyke-5.3.2 lib/spyke/associations/builder.rb
spyke-5.3.1 lib/spyke/associations/builder.rb
spyke-5.3.0 lib/spyke/associations/builder.rb
spyke-5.2.0 lib/spyke/associations/builder.rb
spyke-5.1.0 lib/spyke/associations/builder.rb
spyke-5.0.0 lib/spyke/associations/builder.rb
spyke-4.1.1 lib/spyke/associations/builder.rb
spyke-4.1.0 lib/spyke/associations/builder.rb
spyke-4.0.1 lib/spyke/associations/builder.rb
spyke-4.0.0 lib/spyke/associations/builder.rb
spyke-3.1.5 lib/spyke/associations/builder.rb
spyke-3.1.4 lib/spyke/associations/builder.rb