Alessandro De Simone
Alessandro De Simone

Reputation: 4215

Uninitialized constant trying to reopen a Class

I am using a plugin in Rails, and I call its methods without problems:

plugin_module::class_inside_module.method_a(...)

I want to re-open the class_inside_module and add a new method, I tried in many different ways. I can't figure out why in this way doesn't work:

class plugin_module::class_inside_module
  def new_method
    puts 'new method'
  end
end

I get the error: uninitialized constant plugin_module, but how is possible if I can call without problem plugin_module::class_inside_module.any_methods ?

Do you know why I get that error ? why "uninitialized constant" ? (it is a class declaration :-O )

Do you have any ideas how I can add a new methods in a class inside a module (that is part of a plugin) ?

Thank you, Alessandro

Upvotes: 1

Views: 355

Answers (2)

nathanvda
nathanvda

Reputation: 50057

If you have written your class and module-names like you did, so plugin_module instead of PluginModule this is against ruby/rails standards, and rails will not be able to automatically find the class and module.

If you write something like

module MyModule
  class MyClass

  end
end

Rails will expect this file to be located in lib\my_module\my_class. But this can always easily be overwritten by explicitly doing a require.

So in your case, when you write

module plugin_module::class_inside_module

Rails will not know where to find the module plugin_module. This way of writing only works if module plugin_module is previously defined (and loaded).

So either add the correct require, or rename your modules to standard rails naming, or write it as follows:

module plugin_module
  class class_inside_module

This way will also work, because now the order no longer matters. If the module is not known yet, this will define the module as well. Either you are re-opening the class, or you define it first (and the actual definition will actually reopen it).

Hope this helps.

Upvotes: 2

Rob Cameron
Rob Cameron

Reputation: 9786

Have you tried reopening the module that's wrapping the class, rather than relying on ::?

module plugin_module
  class class_inside_module
    def new_method
      puts 'new_method'
    end
  end
end

By the way, you know that the proper name for modules and classes is use CamelCase with a capital first letter?

module PluginModule
  class ClassInsideModule
    def new_method
      puts 'new_method'
    end
  end
end

Upvotes: 1

Related Questions