Search code examples
ruby-on-railsrubymodel

ruby on rails constantize method


I came across the following in the model:

class Search < ActiveRecord::Base
  #search different system user by dn
  def self.gets(sys, dn)
    sys.constantize.search(dn)
  end
end

I can see the purpose is to pass in different model name as sys and search by dn in those specific models. However, I searched on constantize in Ruby and couldn't see any detailed explanation about this usage.


Solution

  • Rails documentation (because constantize is a Rails method) says:

    Tries to find a constant with the name specified in the argument string.

    For instance, if you have a model called Foo in your application, then you can apply the constantize method to a string, which contains the exact word Foo, and it'll give you a new object with this model. Note this must be capitalized as Rails would work with your model, if you do a bad reference, then you'll get a NameError error:

    NameError: wrong constant name foo
    

    How does it do it?, if you go to the method definition, or if you playing with the method get an error, you'll see the source points to activesupport-5.1.5/lib/active_support/inflector/methods.rb:269:in 'const_get', which is the method definition and the error source.

    Between the cases the method handles internally depending on what's being received as argument, you'll see the Object.const_get(string) which is the way Ruby (pure) handles a "constantiz-ation", which would be the same as doing

    Object.const_get('Foo') # Foo(...)
    Object.const_get('foo') # NameError: wrong constant name foo
    

    If thinking on implement this handy method, you could take a look to the Gavin Miller's post from some years ago.