Method: SimpleCommand::KlassTransform#to_modules_string

Defined in:
lib/simple_command_dispatcher/klass_transform.rb

#to_modules_string(klass_modules = [], options = {}) ⇒ String

Returns a string of modules that can be subsequently prepended to a class, to create a constantized class.

Examples:


to_modules_string("Api") # => "Api::"
to_modules_string([:Api, :AppName, :V1]) # => "Api::AppName::V1::"
to_modules_string({ :api :Api, app_name: :AppName, api_version: :V1 }) # => "Api::AppName::V1::"
to_modules_string({ :api :api, app_name: :app_name, api_version: :v1 }, { module_titleize: true })
   # => "Api::AppName::V1::"

Parameters:

  • klass_modules (Hash, Array or String) (defaults to: [])

    the modules a class belongs to.

  • options (Hash) (defaults to: {})

    the options that determine how klass_modules is transformed.

Options Hash (options):

  • :module_titleize (Boolean) — default: false

    Determines whether or not klass_modules should be titleized.

Returns:

  • (String)

    a string of modules that can be subsequently prepended to a class, to create a constantized class.

Raises:

  • (ArgumentError)

    if the klass_modules is not of type String, Hash or Array.



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/simple_command_dispatcher/klass_transform.rb', line 97

def to_modules_string(klass_modules = [], options = {})
  klass_modules = validate_klass_modules(klass_modules)

  options = ensure_options(options)

  klass_modules_string = ''
  unless klass_modules.empty?
    case klass_modules
    when String
      klass_modules_string = klass_modules
    when Array
      klass_modules_string = klass_modules.join('::').to_s
    when Hash
      klass_modules_string = ''
      klass_modules.to_a.each_with_index.map do |value, index|
        klass_modules_string = index.zero? ? value[1].to_s : "#{klass_modules_string}::#{value[1]}"
      end
    else
      raise ArgumentError, 'Class modules is not a String, Hash or Array.'
    end
    klass_modules_string = klass_modules_string.split('::').map(&:titleize).join('::') if options[:module_titleize]
    klass_modules_string = camelize(klass_modules_string) if options[:module_camelize]
    klass_modules_string = klass_modules_string.trim_all
    klass_modules_string = "#{klass_modules_string}::" unless klass_modules_string.empty?
  end

  klass_modules_string
end