Henry Yang
Henry Yang

Reputation: 2573

How to dynamically get Class in Ruby just like we can call send to trigger a method dynamically?

I know we can do this:

Person.send(:new)

But let's say we have this code:

class Person
  def self.plural
    'people'
  end
end

Is there a way that allows us to do this?

klass = Class.get_class('Person')
klass.send(:plural)
# => 'people'

What's the name of this concept?

Is this a bad practice?

Upvotes: 0

Views: 187

Answers (2)

cdadityang
cdadityang

Reputation: 543

Yes, you can do something like this, for dynamically in rails, script would be something like this:

# => class_send("Article", :new)

def class_send(class_name, send_name)
  classes_array = ApplicationRecord.subclasses.collect(&:name)
  # => ["User", "Article"] - returns all models names
  
  get_index = classes_array.index(class_name)
  # => 1
  
  req_class = Object.const_get classes_array[get_index]
  # => Article Class
  
  req_class.send(send_name)
  # => Runs Article.new
end

Upvotes: 1

Ninh Le
Ninh Le

Reputation: 1331

Ruby actually allows you get the class object from the argument in the string by using const_get. For example

klass = Object.const_get("Person") # => return Person class

Upvotes: 3

Related Questions