Ruby:向现有模块添加方法

fre*_*oid 3 ruby module metaprogramming ruby-on-rails ruby-on-rails-3

有一个模块:

module ActionDispatch
  module Routing
  end
end
Run Code Online (Sandbox Code Playgroud)

以及方法:

def add_movie_path
end

def edit_movie_path
end
Run Code Online (Sandbox Code Playgroud)

如何将这种方法添加到模块路由

是唯一的方法吗?

My *_*God 5

尝试:

module ActionDispatch
  module Routing
    def add_movie_path
    end

    def edit_movie_path
    end
     module_function :edit_movie_path
  end
end
Run Code Online (Sandbox Code Playgroud)

这样您就可以像实例方法一样进行调用,如下所示:

class Make
   include ActionDispatch::Routing
end 


class MakeAll
   def only_needs_the_one_method
      ActionDispatch::Routing.edit_movie_path
   end
end 
Run Code Online (Sandbox Code Playgroud)

您还可以通过使用将其定义为类方法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
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅Modules Magic 。