开发者

Uninitialized constant trying to reopen a Class

开发者 https://www.devze.com 2023-04-06 18:15 出处:网络
I am using a plugin in Rails, and I call its methods without problems: plugin_module::class_inside_module.method_a(...)

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


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消