0

I'm trying to recreate a case_class (like from Scala) but in Ruby. so I've tried

def case_class name
  Object.const_set name, Class.new {}
end 

but I get: NameError: uninitialized constant ...

I have tried to find which method throws that error, but I couldn't find it. for ex. redefining "const_missing" in Object but I keep getting the same error

OlivierBlanvillain
  • 7,701
  • 4
  • 32
  • 51
  • With your code and calling `case_class('Demo')` it makes a class called "Demo" and there's no errors. Remember you'll have to do this prior to using that class in any code, or possibly loading any files which reference that class during parsing. – tadman Apr 07 '17 at 06:19
  • Yeah but I'm trying not to call it that way. It need to work without parenthesis, just like "case_class Demo" – FrankIglesias Apr 07 '17 at 06:25
  • Nope, can't do that. The only way that code's valid is if `Demo` is a valid constant, which it isn't until that method is done. Catch-22. – tadman Apr 07 '17 at 06:25
  • You can also set the constant from within the `Class.new` block, i.e.: `Class.new { |klass| Object.const_set(name, klass) }` – Stefan Apr 07 '17 at 06:26
  • @FrankIglesias BTW, do you think this is a duplicate? Does the other question help you to solve the problem? – Stefan Apr 07 '17 at 06:27
  • @Stefan I read the other question, but I keep having the same constant error. I'm trying to figure out who handles the constants that don't exist – FrankIglesias Apr 07 '17 at 06:31
  • `Yeah but I'm trying not to call it that way. It need to work without parenthesis, just like "case_class Demo"` - your code works throwing no errors. – Andrey Deineko Apr 07 '17 at 06:40
  • @FrankIglesias _"who handles the constants that don't exist"_ – [`Module.const_missing`](http://ruby-doc.org/core-2.4.1/Module.html#method-i-const_missing) – Stefan Apr 07 '17 at 06:54
  • @Stefan it works!!!!!! Thank u very much – FrankIglesias Apr 07 '17 at 07:02

0 Answers0