Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uninitialized constant MyClass (NameError) in Ruby

Tags:

ruby

I have a module Shish(which acts like an abstract class) and a visitor class Only_Onions.

I want to instantiate Only_Onions in the module Shish so that all the classes extending Shish can use the object to deteremine if they have only__onions.

module Shish
    only_onions_class = Only_Onions.new
end

class Only_Onions
    def for_skewer
        return true
    end
end


class Skewer
    include Shish

    def only_onions
        return only_onions_class.for_skewer
    end

    def veg?
        return true
    end
end

But I get an error "uninitialized constant Shish::Only_Onions (NameError). What does that mean?

like image 426
unj2 Avatar asked May 16 '09 16:05

unj2


2 Answers

The order of declaration has an effect. Shish doesn't know about Only_Onions in your code. If you change it to this, then Only_Onions is already declared when you define the module Shish:

class Only_Onions
    def for_skewer
        return true
    end
end

module Shish
    only_onions_class = Only_Onions.new
end

class Skewer
    include Shish

    def only_onions
        return only_onions_class.for_skewer
    end

    def veg?
        return true
    end
end
like image 55
pez_dispenser Avatar answered Nov 13 '22 14:11

pez_dispenser


try

::Only_Onions
like image 28
John Douthat Avatar answered Nov 13 '22 13:11

John Douthat