Module: ClassExt
- Defined in:
- lib/sweetloader.rb
Defined Under Namespace
Classes: ClassNotFoundError, ModuleNotFoundError
Instance Method Summary
collapse
Instance Method Details
#class_exists?(name) ⇒ Boolean
80
81
82
83
84
|
# File 'lib/sweetloader.rb', line 80
def class_exists?(name)
is_class? get_module(name)
rescue
return false
end
|
#find_first_class(*names) ⇒ Object
117
118
119
120
121
122
123
124
125
|
# File 'lib/sweetloader.rb', line 117
def find_first_class *names
classes = names.flatten.compact.uniq.inject([]) do |res, class_name|
found_class = try_class(class_name.to_s.camelize)
res << found_class if found_class
res
end
raise ClassNotFoundError, "Not one Class for any of: #{names} is currently loaded" if classes.empty?
classes.first
end
|
#find_first_module(*names) ⇒ Object
127
128
129
130
131
132
133
134
135
|
# File 'lib/sweetloader.rb', line 127
def find_first_module *names
modules = names.flatten.compact.uniq.inject([]) do |res, class_name|
found_class = try_module(class_name.to_s.camelize)
res << found_class if found_class
res
end
raise ModuleNotFoundError, "Not one Module for any of: #{names} is currently loaded" if modules.empty?
modules.first
end
|
#get_module(name) ⇒ Object
65
66
67
68
69
70
|
# File 'lib/sweetloader.rb', line 65
def get_module name
name.to_s.camelize.constantize
rescue
nil
end
|
#is_class?(clazz) ⇒ Boolean
72
73
74
|
# File 'lib/sweetloader.rb', line 72
def is_class?(clazz)
clazz.is_a?(Class) && (clazz.respond_to? :new)
end
|
#is_module?(clazz) ⇒ Boolean
76
77
78
|
# File 'lib/sweetloader.rb', line 76
def is_module?(clazz)
clazz.is_a?(Module) && !(clazz.respond_to? :new)
end
|
#module_exists?(name) ⇒ Boolean
86
87
88
89
90
|
# File 'lib/sweetloader.rb', line 86
def module_exists?(name)
is_module? get_module(name)
rescue NameError
return false
end
|
#try_class(name) ⇒ Object
92
93
94
95
96
97
98
|
# File 'lib/sweetloader.rb', line 92
def try_class name
return name if name.kind_of?(Class)
found = get_module(name) if name.is_a?(String) || name.is_a?(Symbol)
return found if found.is_a?(Class)
rescue
false
end
|
#try_module(name) ⇒ Object
100
101
102
103
104
105
106
|
# File 'lib/sweetloader.rb', line 100
def try_module name
return name if name.kind_of?(Module)
found = get_module(name.to_s) if name.is_a?(String) || name.is_a?(Symbol)
return found if found.is_a?(Module)
rescue
false
end
|
#try_module_only(name) ⇒ Object
108
109
110
111
112
113
114
|
# File 'lib/sweetloader.rb', line 108
def try_module_only name
return name if is_module?(name)
found = get_module(name) if name.is_a?(String) || name.is_a?(Symbol)
return found if is_module?(found)
rescue
false
end
|