简体   繁体   中英

Rails - Check if model is modulized

Is there a way to check for any namespace in a model?

ie this is what I would be looking for

Foo::Bar.modulized? = true
Bar.modulized? = false

The check is for any namespace not for a particular module

You can try this

Foo::Bar.ancestors.select {|o| o.class == Module }.include?(Foo)

or

Foo::Bar.included_modules.include?(Foo)

To check if the Model has any namespace or not you can do this

Foo::Bar.parent == Foo #=> true 

or simply

Foo::Bar.parent.is_a? Module #=> true   

Hope that helps!

I'd do this:

ActiveRecord::Base.name.include?('ActiveRecord::') # => true

To check if model is modulized with any module, just do:

ActiveRecord::Base.name.include?('::')

But, be aware that it'll return true for inner classes:

class Main
  class Inner
  end
end

clazz = Main::Inner
clazz.name.include?('::')

Hope it helps!

I think there is no such method, but you can use Module::nesting to implement it, for instance if you have a nested class:

module A
  class B
    puts Module.nesting.inspect
  end
end

The output of the previous code is: [A::B, B]

If your class is not nested:

class C
   puts Module.nesting.inspect
end

The output will be: [C]

So, you can create a module with the modulized? class method:

-Create a file called active_record_extension.rb in the lib directory.

module ActiveRecordExtension
  extend ActiveSupport::Concern

  module ClassMethods
    def modulized?
      Module.nesting.size > 1
    end
  end
end

ActiveRecord::Base.send(:include, ActiveRecordExtension)

Create a file in the config/initializers directory called extensions.rb and add the following line to the file:

require "active_record_extension"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM