Module: SchemaMonkey::ModuleSupport

Included in:
SchemaMonkey
Defined in:
lib/schema_monkey/module_support.rb

Instance Method Summary collapse

Instance Method Details

#get_const(mod, name) ⇒ Object

ruby 2.* supports mod.const_get(“Component::Path”) but ruby 1.9.3 doesn’t. And neither has a version that can return nil rather than raising a NameError



23
24
25
26
27
28
29
30
31
32
# File 'lib/schema_monkey/module_support.rb', line 23

def get_const(mod, name)
  name.to_s.split('::').map(&:to_sym).each do |component|
    begin
      mod = mod.const_get(component, false)
    rescue NameError
      return nil
    end
  end
  mod
end

#get_modules(parent, opts = {}) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/schema_monkey/module_support.rb', line 34

def get_modules(parent, opts={})
  opts = opts.keyword_args(:prefix, :match, :reject, :recursive, :respond_to, :and_self)
  parent = get_const(parent, opts.prefix) if opts.prefix
  return [] unless parent && parent.is_a?(Module)
  modules = []
  modules << parent if opts.and_self
  modules += parent.constants.reject{|c| parent.autoload? c}.map{|c| parent.const_get(c)}.select(&it.is_a?(Module))
  modules.reject! &it.to_s =~ opts.reject if opts.reject
  modules.select! &it.to_s =~ opts.match if opts.match
  modules.select! &it.respond_to?(opts.respond_to) if opts.respond_to
  modules += modules.flat_map { |mod| get_modules(mod, opts.except(:prefix, :and_self)) } if opts.recursive
  modules
end

#include_if_defined(base, parent, subname) ⇒ Object



8
9
10
11
12
# File 'lib/schema_monkey/module_support.rb', line 8

def include_if_defined(base, parent, subname)
  if submodule = get_const(parent, subname)
    include_once(base, submodule)
  end
end

#include_once(base, mod) ⇒ Object



4
5
6
# File 'lib/schema_monkey/module_support.rb', line 4

def include_once(base, mod)
  base.send(:include, mod) unless base.include? mod
end

#patch(base, parent = SchemaMonkey) ⇒ Object



14
15
16
17
18
# File 'lib/schema_monkey/module_support.rb', line 14

def patch(base, parent = SchemaMonkey)
  patch = get_const(parent, base)
  raise "#{parent} does not contain a definition of #{base}" unless patch
  include_once(base, patch)
end