简体   繁体   English

Ruby:向现有模块添加方法

[英]Ruby: add method to the existing module

There is a module: 有一个模块:

module ActionDispatch
  module Routing
  end
end

And methods: 和方法:

def add_movie_path
end

def edit_movie_path
end

How I can add to module Routing this methods? 我如何添加到模块路由这种方法呢?

Is this only way? 就是唯一的办法?

Try: 尝试:

module ActionDispatch
  module Routing
    def add_movie_path
    end

    def edit_movie_path
    end
     module_function :edit_movie_path
  end
end

So that then you can do a call like it is a instance method like so: 这样您就可以像调用实例方法那样进行调用:

class Make
   include ActionDispatch::Routing
end 


class MakeAll
   def only_needs_the_one_method
      ActionDispatch::Routing.edit_movie_path
   end
end 

You can also define it as a class method by using self.class_name and then directly access it like so: 您还可以通过使用self.class_name将其定义为类方法 ,然后像这样直接访问它:

module ActionDispatch
  module Routing
    def self.add_movie_path
    end

    def self.edit_movie_path
    end
  end
end

class Make
    include ActionDispatch::Routing
   def do_something
     ActionDispatch::Routing.add_movie_path
   end
end 


class MakeAll
   def only_needs_the_one_method
      ActionDispatch::Routing.edit_movie_path
   end
end

See that Modules Magic for more. 有关更多信息,请参见该模块魔术

Unless I misunderstand what you're asking, how about something like: 除非我误解了您的要求,否则类似:

module ActionDispatch
  module Routing
    def add_movie_path
    end

    def edit_movie_path
    end
  end
end

Alternatively, you could use module_eval . 另外,您可以使用module_eval

Simply put your methods inside the module. 只需将您的方法放入模块中即可。

module ActionDispatch
  module Routing
    def add_movie_path
    end

    def edit_movie_path
    end  
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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