Sha256: f239b64e57773b680160dc6b59de627b52cb884adbf61da8bbe16be6aa49574b

Contents?: true

Size: 1.24 KB

Versions: 4

Compression:

Stored size: 1.24 KB

Contents

module SchemaMonkey
  module Module
    extend self

    def insert(base, mod)
      if mod.respond_to? :included
        base.send(:include, mod) unless base.include? mod
      else
        base.send(:prepend, mod)
      end
    end

    # ruby 2.* supports mod.const_get("Component::Path") but ruby 1.9.3
    # doesn't.  And neither has an option to return nil rather than raising
    # a NameError
    def const_lookup(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

    def descendants(mod, can_load: nil)
      consts, auto = mod.constants.group_by{|c| !!mod.autoload?(c)}.values_at(false, true)
      consts ||= []
      consts += auto.select { |it| it.to_s =~ can_load } if can_load and auto
      children = consts.map{|c| mod.const_get(c) }.select { |obj|
        obj.is_a?(::Module) rescue nil
      }
      children + children.flat_map {|c| descendants(c, can_load: can_load) }
    end

    def mkpath(mod, path)
      path.split('::').each do |component|
        mod = const_lookup(mod, component) || mod.const_set(component, ::Module.new)
      end
      mod
    end

  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
schema_monkey-3.0.1 lib/schema_monkey/module.rb
schema_monkey-3.0.0 lib/schema_monkey/module.rb
schema_monkey-2.1.6 lib/schema_monkey/module.rb
schema_monkey-2.1.5 lib/schema_monkey/module.rb