How to find out which modules are mixin for a class in Rails?

I am the new Ruby / Rails guy. Here one question puzzles me:

Can we find the exact lists of mixin-ed modules for a class in Rails from an API document? For example, if we have an instance of one subclass of ActiveRecord :: Base, we can use the verification method in this class, for example:

class Product < ActiveRecord::Base has_many :line_items validates :title, :description, :image_url, :presence => true end 

from the rails api doc we can find that validates belongs to ActiveModel :: Validations :: ClassMethods, so ActiveRecore :: Base should have ActiveModel :: Validations :: ClassMethods mixin, but I did not find anything that related to this in the api link. Can someone tell me if I can find this information from api doc?

Thanks for your help in advance. I really hope my question doesn't sound too stupid :)

+8
ruby ruby-on-rails
source share
3 answers

I don't see anything like this in any of the Rails documentation I saw:

And with the monkey patch, there is probably no way to find out until Rails is up and you have a valid ActiveRecord :: Base in your hands; for example, PostgreSQL, MySQL, and SQLite adapters reopen ActiveRecord :: Base, and they may include additional modules along the way; other gems you use, and even your own code can do similar things.

If you just want to find out the standard mixins set, use the source (Luke!) Or do as prompted and ask ActiveRecord :: Base in the Rails console.

In general, the Rails API documentation is not so useful if you don’t already know what you are looking for, and even then, you often need to dig in the source.

It is best to check guides for what you need and read the source if this does not work.


The short answer . You cannot get your list from the documentation, because the modules cannot be known before starting. Read the guides and source if you need to know something.

+3
source share

in console:

 ActiveRecord::Base.included_modules 
+8
source share

Short answer: you cannot.

The long answer is just an excuse (lousy): Ruby and Rails documentation is automatically generated from the source. And Ruby is known for its metaprogramming capabilities, so the fact that the method is included in the class cannot be (easily) extracted by analyzing the source. The only reliable way to get a list of methods in a class is to start the console and type SomeVeryImportantClass.methods .

However, it really discourages and disappoints both new and experienced developers who cannot easily find some of the most commonly used methods in documents. This is disappointing that someone did not think about how to somehow include these cross-references, perhaps even manually.

+1
source share

All Articles