An alternative to constantize in ActiveSupport.

I saw a nice alternative when ActiveSupport constantize or eval in the rom-rb codebase today, get_const.

This is useful for libraries and applications which do not already have ActiveSupport as a dependency.

Here is an example:

class AdapterBase
  def command(name, options)
    klass = 
      case name
      when :create then self.class.const_get(:Create)
      when :update then self.class.const_get(:Update)
      when :delete then self.class.const_get(:Delete)
      else
        raise ArgumentError, '...'
      end

    klass.new.call(options)
  end
end

class MyAdapter < AdapterBase
  class Create
    def call(options)
      # ...
    end
  end
end

adapter = MyAdapter.new
adapter.command(:create, {...}) # this will call MyAdapter::Create

If you also need inflections such as classify, underscore, dasherize you might want to consider the Inflecto gem which also includes constantize.