Sha256: d66c802a0724378f24dda73b1e5beb099e165abb4791e43638fd6c4e530a64df

Contents?: true

Size: 732 Bytes

Versions: 4

Compression:

Stored size: 732 Bytes

Contents

# frozen_string_literal: true

module Clowne
  module Ext
    # Add simple constantize method to String
    module StringConstantize
      refine String do
        def constantize
          names = split("::")

          return nil if names.empty?

          # Remove the first blank element in case of '::ClassName' notation.
          names.shift if names.size > 1 && names.first.empty?

          begin
            names.inject(Object) do |constant, name|
              constant.const_get(name)
            end
          # rescue instead of const_defined? allow us to use
          # Rails const autoloading (aka patched const_get)
          rescue NameError
            nil
          end
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
clowne-1.5.0 lib/clowne/ext/string_constantize.rb
clowne-1.4.0 lib/clowne/ext/string_constantize.rb
clowne-1.3.0 lib/clowne/ext/string_constantize.rb
clowne-1.2.0 lib/clowne/ext/string_constantize.rb