An Alterntive to Constantize

- - posted in ruby | Comments

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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.

Comments