sschmeck
sschmeck

Reputation: 7685

How to access a dynamically created class within another?

I've no idea how I can access a dynamically created class within another one. The classes are stored in local variables and I want to avoid using constants instead since the classes are created within a method.

def clazzes_and_clazzes
  clazz_one = Class.new do
    def one; 'one'; end
  end
  puts clazz_one.new.one

  clazz_two = Class.new do
    def two
      clazz_one.new.one + ' and ' + clazz_one.new.one
    end
  end
  puts clazz_two.new.two

  clazz_two
end

clazzes_and_clazzes

I expect the following output.

$ ruby snippet.rb
one
one and one

But the snippet above raises the following error message.

snippet.rb:9:in `two': undefined local variable or method `clazz_one' for #<#<Class:0x7f2fa401af10>:0x7f2fa401ae98> (NameError)
    from snippet.rb:12:in `clazzes_and_clazzes'
    from snippet.rb:15

How could I resolve the error?

Upvotes: 1

Views: 46

Answers (1)

Marek Lipka
Marek Lipka

Reputation: 51151

You're out of the scope in which clazz_one is defined when you use def keywords to define method. Instead, you can use define_method method, which takes a block, which is closure, so it preserves the local scope:

define_method :two do
  clazz_one.new.one + ' and ' + clazz_one.new.one
end

Here you can learn more about scopes in Ruby: http://www.sitepoint.com/understanding-scope-in-ruby/

Upvotes: 3

Related Questions