module Corefines::Support::AliasSubmodules

@private When this module is included, then it:

  1. Defines an “alias” for each submodule, i.e. singleton method that returns the submodule and it's named after the submodule, but the name is converted to underscore_separated or an operator. For example, instead of using Corefines::String::ToHtml one can write using Corefines::String::to_html.

  2. Includes all the submodules into the module. This allows to use all refinements inside the submodules just by using their parent module.

  3. Defines method {[]}.

@!method self.[](*names)

@example
  Corefines::Object[:blank?, :then]

@param names [Array<Symbol>] names of submodules aliases to include
  into the returned module.
@return [Module] a new module that includes the named submodules.

Constants

OPERATORS_MAP

Private Class Methods

included(target) click to toggle source
# File lib/corefines/support/alias_submodules.rb, line 57
def self.included(target)
  target.constants.each do |const|
    submodule = target.const_get(const)
    next unless submodule.instance_of? ::Module

    # Defines method-named "alias" for the submodule. (1)
    target.define_singleton_method(method_name(const)) { submodule }

    # Includes the submodule of the target into target. (2)
    target.send(:include, submodule)
  end

  target.extend ClassMethods
end
method_name(module_name) click to toggle source
# File lib/corefines/support/alias_submodules.rb, line 72
def self.method_name(module_name)
  name = underscore(module_name)
  OPERATORS_MAP[name.to_sym] || name
end
underscore(camel_cased_word) click to toggle source
# File lib/corefines/support/alias_submodules.rb, line 77
def self.underscore(camel_cased_word)
  return camel_cased_word unless camel_cased_word =~ /[A-Z]/

  camel_cased_word.to_s.dup.tap do |s|
    s.gsub! /([A-Z\d]+)([A-Z][a-z])/, '\1_\2'
    s.gsub! /([a-z\d])([A-Z])/, '\1_\2'
    s.downcase!
  end
end