Sha256: 9cdd54e2a659c77f746e7326fac4b756e3fbf43faf300024a1c896b8d322d7a8

Contents?: true

Size: 1.43 KB

Versions: 12

Compression:

Stored size: 1.43 KB

Contents

class Releaf::Builders
  def self.builder_class(scopes, type)
    (scopes + inherited_builder_scopes).each do |scope|
      builder_class = builder_class_at_scope(scope, type)
      return builder_class if builder_class
    end

    raise ArgumentError, "unexisting builder (type: #{type}; scopes: #{scopes.join(", ")})"
  end

  def self.builder_class_at_scope(scope, type)
    builder_class_name = "#{scope}::#{type.to_s.camelize}Builder"

    if constant_defined_at_scope?(scope, Object) && constant_defined_at_scope?(builder_class_name, scope.constantize)
      builder_class_name.constantize
    end
  end

  def self.constant_defined_at_scope?(mapping, at)
    constant_defined = false

    begin
      constant_defined = at.const_get(mapping).present? && mapping.constantize == at.const_get(mapping)
    rescue NameError => error
      raise unless constant_name_error?(error.message, mapping)
    end

    constant_defined
  end

  def self.constant_name_error?(error_message, mapping)
    # rails5 have anonymous classes while in production env for error messags
    # ex. `Caused by NameError: uninitialized constant #<Class:0x00007fc1b79e8448>::AnotherFormBuilder` instead of
    # `Caused by NameError: uninitialized constant Releaf::Builders::AnotherFormBuilder`
    (error_message =~ /#{mapping.split("::").last}$/).present?
  end

  def self.inherited_builder_scopes
    (ancestors.grep(Class) - [Object, BasicObject]).collect{|c| c.name }
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
releaf-core-3.1.0 app/builders/releaf/builders.rb
releaf-core-3.0.3 app/builders/releaf/builders.rb
releaf-core-3.0.2 app/builders/releaf/builders.rb
releaf-core-3.0.1 app/builders/releaf/builders.rb
releaf-core-3.0.0 app/builders/releaf/builders.rb
releaf-core-2.2.1 app/builders/releaf/builders.rb
releaf-core-2.2.0 app/builders/releaf/builders.rb
releaf-core-2.1.2 app/builders/releaf/builders.rb
releaf-core-2.1.1 app/builders/releaf/builders.rb
releaf-core-2.1.0 app/builders/releaf/builders.rb
releaf-core-2.0.1 app/builders/releaf/builders.rb
releaf-core-2.0.0 app/builders/releaf/builders.rb