Define a constant in dynamically defined class

Have me a conundrum.

     k = Class.new() do
       class X; end
     end

    k::X.object_id

results in

    (irb):7: warning: toplevel constant X referenced by #<Class:
0x00000001954380>::X

I don't want X to be toplevel. I want it to be under `k`. To
complicate matters I don't have control over the block, as it actually
comes from a testing procedure defined by an end user. The actual code
is this:

      # Create a sub-case.

···

#
       def context(desc=nil, &block)
        cls = Class.new(TestCase, &block)
        cls.desc(desc) if desc
        cls
      end

Is there any way to isolate X to k? And then apply it to the more
general dynamic case?

Thanks.

You could do this:

k = Class.new do
  class_eval("class X; end")
end

puts k::X.object_id

···

On Tue, Jul 5, 2011 at 10:15 AM, Intransition <transfire@gmail.com> wrote:

Have me a conundrum.

    k = Class.new() do
      class X; end
    end

   k::X.object_id

results in

   (irb):7: warning: toplevel constant X referenced by #<Class:
0x00000001954380>::X

I don't want X to be toplevel. I want it to be under `k`. To
complicate matters I don't have control over the block, as it actually
comes from a testing procedure defined by an end user. The actual code
is this:

     # Create a sub-case.
     #
      def context(desc=nil, &block)
       cls = Class.new(TestCase, &block)
       cls.desc(desc) if desc
       cls
     end

Is there any way to isolate X to k? And then apply it to the more
general dynamic case?

Thanks.

      k = Class.new() do
        class X; end
      end

     k::X.object_id

results in

     (irb):7: warning: toplevel constant X referenced by #<Class:
0x00000001954380>::X

[...]

Is there any way to isolate X to k? And then apply it to the more
general dynamic case?

Thanks.

You can use Module#const_set.

const_set :X, Class.new

Entering the block scope does not automatically change the current context for constant definition (the core developers call it the `cref'), nor does instance_eval and class_eval.

···

On 7/5/2011 10:15 AM, Intransition wrote:

Thanks, but unfortunately that only works b/c it's evaluating a string
and not a block.

I tried this thinking it should do the trick:

  Class.new do
   instance_eval(&block)
  end

But no go :frowning:

···

On Jul 5, 10:45 am, Mike Bethany <mikbe...@gmail.com> wrote:

You could do this:

k = Class.new do
class_eval("class X; end")
end

puts k::X.object_id

I've been reading up on this[1]. Looks like the was a period (1.9.1)
when it didn't work this way. I am inclined to think it a bug. At the
very least there has to be work around.

[1]http://jfire.posterous.com/constant-lookup-in-ruby

···

On Jul 5, 7:57 pm, Su Zhang <su.comp.lang.r...@gmail.com> wrote:

Entering the block scope does not automatically change the current
context for constant definition (the core developers call it the
`cref'), nor does instance_eval and class_eval.