Convert String to Class Name Without Using Eval in Ruby

Convert string to class name without using eval in ruby?

You can try

class Post
end

Object.const_get("Post")

Which returns the Post class

ruby convert class name in string to actual class

I think what you want is constantize

That's an RoR construct. I don't know if there's one for ruby core

ALternative to eval for string

If you require Active Record, you can use constantize (see here)

So for example, something like this:

require "active_record"

"Mymodel::FirstClass".constantize
=> Mymodel::FirstClass

Or you can use const_get

Kernel.const_get("Mymodel::FirstClass")
=> MyModel::FirstClass

Take String (Ex. Car ) and turn it into Class in Ruby

You could use const_get:

klazz = Object.const_get('Broseph')

Then call methods on klazz like:

klazz.some_method # when you know the method is fixed
klazz.send('some_method') # when the method also is stored in a string

Cast between String and Classname

This solution is better than eval as you are evaluating params hash that might be manipulated by the user and could contain harmful actions. As a general rule: Never evaluate user input directly, that's a big security hole.

# Monkey patch for String class
class String
def to_class
klass = Kernel.const_get(self)
klass.is_a?(Class) ? klass : nil
rescue NameError
nil
end
end

# Examples
"Fixnum".to_class #=> Fixnum
"Something".to_class #=> nil

Update - a better version that works with namespaces:

 # Monkey patch for String class
class String
def to_class
chain = self.split "::"
klass = Kernel
chain.each do |klass_string|
klass = klass.const_get klass_string
end
klass.is_a?(Class) ? klass : nil
rescue NameError
nil
end
end

Get Java Class represented by a String in JRuby? (without eval)

So I stumbled upon a solution from looking at the JRuby Wiki. Java::JavaClass.for_name can be used to convert the String to a Java class, which can be converted to a Ruby class using ruby_class. Example using IRB:

jruby-1.6.8 :053 > math_class = Java::JavaClass.for_name("java.lang.Math").ruby_class
=> Java::JavaLang::Math
jruby-1.6.8 :054 > math_class.floor( 10.7 )
=> 10.0

How do I convert a string to a class method?

Post.send(anything)

How do I convert a string text into a class name

You could use:

Object.const_get( class_name )

$ irb
>> class Person
>> def name
>> "Person instance"
>> end
>> end
=> nil
>> class_name = "Person"
=> "Person"
>> Object.const_get( class_name ).new.name
=> "Person instance"


Related Topics



Leave a reply



Submit