deepak
deepak

Reputation: 3172

accessing dynamic class name ruby

class_name = "TestClass"
Object.const_set class_name,Class.new{
    include MOduleX
}

#module_x.rb
module ModuleX
    def ModuleX.included (klass)
         p klass.name #=> nil
    end
end

I need to access the name of the class ("TestClass" in this case) inside the module, how can I do it?

Upvotes: 0

Views: 75

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110755

@Amadan has explained why that won't work, but you can get it if you are able to write it like this:

class_name = "Test"

module ModuleX
  def self.included(klass)
    puts "klass = #{klass}"
  end
end

Object.const_set class_name, Class.new do  
end.include ModuleX
  #=> "klass = Test"

Upvotes: 1

Amadan
Amadan

Reputation: 198486

You can't, const_set is occuring after Class.new. At the point where ModuleX is included (MOduleX is, I assume, a typo), the class is well and truly nameless.

Not to even mention that a constant can't be called test, as Ruby grammar mandates that constants must start with a capital letter.

However, if your module must know the class name at inclusion time, it's probably doing something wrong. I suggest rethinking and refactoring.

Upvotes: 2

Related Questions