简体   繁体   中英

Ruby How to call module methods from class in the same namespace

I am new to Ruby and trying to understand the module methods in ruby.

module M1
    def comments 
      if @comments
        @comments
      else
        @comments = []
      end
    end

    def add_comment(comment)
       comments << comment
    end

    class Audio

         <<How do i call add_comment or comments >>
         def someMethod
            add_comment "calling module method from class which is in  same namespace or module"
         end

    end

end

Getting the following exception if I call on Module or Class. (undefined method `add_comment' for M1:Module)

Normally you can cover this off with a lazy initializer :

def comments 
  @comments ||= [ ]
end

Where that populates @comments with an empty array unless it's already defined.

That makes the add_comment method redundant since you can just do:

comments << comment

Without any intermediation.

Now note that the comments method is defined as a mixin method , not as a stand-alone one. That means it doesn't exist until some other module or class calls include on that module.

To make it stand-alone:

def self.comments 
  @comments ||= [ ]
end

Now you can do this:

M1.comments << 'New comment'

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