-
Notifications
You must be signed in to change notification settings - Fork 11
/
builders.rb
41 lines (33 loc) · 1.43 KB
/
builders.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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