Ruby String to Class Name

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

How do I get the name of a Ruby class?

You want to call .name on the object's class:

result.class.name

convert string into class name in rails

You should use constantize to get a class based on it's name in string:

"FlightManager::#{handler.camelize}".constantize.calculate())

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

How to instantiate class from name string in Rails?

klass = Object.const_get "ClassName"

about class methods

class KlassExample
def self.klass_method
puts "Hello World from Class method"
end
end
klass = Object.const_get "KlassExample"
klass.klass_method

irb(main):061:0> klass.klass_method
Hello World from Class method

How do I create a class instance from a string name in ruby?

In rails you can just do:

clazz = 'ExampleClass'.constantize

In pure ruby:

clazz = Object.const_get('ExampleClass')

with modules:

module Foo
class Bar
end
end

you would use

> clazz = 'Foo::Bar'.split('::').inject(Object) {|o,c| o.const_get c}
=> Foo::Bar
> clazz.new
=> #<Foo::Bar:0x0000010110a4f8>


Related Topics



Leave a reply



Submit