Ruby on rails Rails 3,包括控制器内的嵌套模块
我有一个控制器,我想包括一些标准方法Ruby on rails Rails 3,包括控制器内的嵌套模块,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有一个控制器,我想包括一些标准方法 class Main::UsersController < Main::BaseController include MyModule::ControllerMethods end 对类方法使用extend而不是include。您还应拆分模型和控制器模块: module MyModule module ModelMethods def acts_as_something send :has_one, :examp
class Main::UsersController < Main::BaseController
include MyModule::ControllerMethods
end
对类方法使用extend而不是include。您还应拆分模型和控制器模块:
module MyModule
module ModelMethods
def acts_as_something
send :has_one, :example, :autosave => true
send :before_create, :make_awesome
send :include, InstanceMethods
end
module InstanceMethods
...
end
end
module ControllerMethods
...
# I want to include these in my controller
def hello; end
def world; end
end
end
ActiveRecord::Base.extend MyModule::ModelMethods
然后,您的模型将如下所示:
class Model < ActiveRecord::Base
acts_as_something
end
对类方法使用extend而不是include。您还应拆分模型和控制器模块:
module MyModule
module ModelMethods
def acts_as_something
send :has_one, :example, :autosave => true
send :before_create, :make_awesome
send :include, InstanceMethods
end
module InstanceMethods
...
end
end
module ControllerMethods
...
# I want to include these in my controller
def hello; end
def world; end
end
end
ActiveRecord::Base.extend MyModule::ModelMethods
然后,您的模型将如下所示:
class Model < ActiveRecord::Base
acts_as_something
end
Yehuda Katz的这篇文章更详细地介绍了为什么仅仅使用extend比覆盖include来扩展更好:只是好奇,你把Base.extend-MyModule::ModelMethods放进去了,但是Base与什么有关呢。它应该是ActiveRecord::Base吗?我原以为使用Base可以使它保持简单,但它可能更容易混淆。我已经将答案更改为使用ActiveRecord::Base。Yehuda Katz的这篇文章更详细地介绍了为什么仅仅使用extend比覆盖include来扩展要好:只是好奇,你把Base.extend MyModule::ModelMethods放在了一起,但是Base与什么有关呢。它应该是ActiveRecord::Base吗?我原以为使用Base可以使它保持简单,但它可能更容易混淆。我已将答案更改为使用ActiveRecord::Base