Module: ClassExt
- Defined in:
- lib/sweetloader.rb
Defined Under Namespace
Classes: ClassNotFoundError, ModuleNotFoundError
Instance Method Summary
collapse
Instance Method Details
#class_exists?(name) ⇒ Boolean
116
117
118
119
120
|
# File 'lib/sweetloader.rb', line 116
def class_exists?(name)
is_class? get_module(name)
rescue
return false
end
|
#find_first_class(*names) ⇒ Object
153
154
155
156
157
158
159
160
161
|
# File 'lib/sweetloader.rb', line 153
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
163
164
165
166
167
168
169
170
171
|
# File 'lib/sweetloader.rb', line 163
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
101
102
103
104
105
106
|
# File 'lib/sweetloader.rb', line 101
def get_module name
name.to_s.camelize.constantize
rescue
nil
end
|
#is_class?(clazz) ⇒ Boolean
108
109
110
|
# File 'lib/sweetloader.rb', line 108
def is_class?(clazz)
clazz.is_a?(Class) && (clazz.respond_to? :new)
end
|
#is_module?(clazz) ⇒ Boolean
112
113
114
|
# File 'lib/sweetloader.rb', line 112
def is_module?(clazz)
clazz.is_a?(Module) && !(clazz.respond_to? :new)
end
|
#module_exists?(name) ⇒ Boolean
122
123
124
125
126
|
# File 'lib/sweetloader.rb', line 122
def module_exists?(name)
is_module? get_module(name)
rescue NameError
return false
end
|
#try_class(name) ⇒ Object
128
129
130
131
132
133
134
|
# File 'lib/sweetloader.rb', line 128
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
136
137
138
139
140
141
142
|
# File 'lib/sweetloader.rb', line 136
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
144
145
146
147
148
149
150
|
# File 'lib/sweetloader.rb', line 144
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
|