Module: ClassExt

Defined in:
lib/sweetloader/class_ext.rb

Defined Under Namespace

Classes: ClassNotFoundError, ModuleNotFoundError

Instance Method Summary collapse

Instance Method Details

#class_exists?(name) ⇒ Boolean

Returns:

  • (Boolean)


20
21
22
23
24
# File 'lib/sweetloader/class_ext.rb', line 20

def class_exists?(name)
  is_class? get_module(name)
rescue
  return false
end

#find_first_class(*names) ⇒ Object

Raises:



57
58
59
60
61
62
63
64
65
# File 'lib/sweetloader/class_ext.rb', line 57

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



67
68
69
70
71
72
73
74
75
# File 'lib/sweetloader/class_ext.rb', line 67

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



5
6
7
8
9
10
# File 'lib/sweetloader/class_ext.rb', line 5

def get_module name
  # Module.const_get(name)
  name.to_s.camelize.constantize
rescue
  nil
end

#is_class?(clazz) ⇒ Boolean

Returns:

  • (Boolean)


12
13
14
# File 'lib/sweetloader/class_ext.rb', line 12

def is_class?(clazz)
  clazz.is_a?(Class) && (clazz.respond_to? :new)
end

#is_module?(clazz) ⇒ Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/sweetloader/class_ext.rb', line 16

def is_module?(clazz)
  clazz.is_a?(Module) && !(clazz.respond_to? :new)
end

#module_exists?(name) ⇒ Boolean

Returns:

  • (Boolean)


26
27
28
29
30
# File 'lib/sweetloader/class_ext.rb', line 26

def module_exists?(name)
  is_module? get_module(name)
rescue NameError
  return false
end

#try_class(name) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/sweetloader/class_ext.rb', line 32

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



40
41
42
43
44
45
46
# File 'lib/sweetloader/class_ext.rb', line 40

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



48
49
50
51
52
53
54
# File 'lib/sweetloader/class_ext.rb', line 48

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