我正在 Rails 中构建一个 gem,它是一个简单的管理界面。我有构建 Rails 应用程序的经验,但这是我第一次开发 gem,我对在 Rails 内部的 gem 部分制作方法的概念有疑问。
例如,我希望我的 gem 中的三个方法可以通过 Rails 应用程序访问。方法有:my_controller_method、my_model_method、my_view_method
# lib/my_gem/view_helpers.rb
module MyGem
module ViewHelpers
def my_view_method(data)
# super mega stuff
end
end
end
# lib/my_gem/active_record.rb
module MyGem
module ActiveRecord
def my_model_method(data)
# super mega stuff
end
end
end
# lib/my_gem/controller_additions.rb
module MyGem
module ControllerAdditions
def my_controller_method(data)
# super mega stuff
end
end
end
所以我希望这些方法在我的 Rails MVC 架构中可用。例如
#app/models/institution.rb
class Institution < ActiveRecord::Base
validates_presence_of :contact_person, :phone_number, :email
my_model_method :some_data
end
#app/controllers/institutions_controller.rb
class InstitutionsController < ApplicationController
my_controller_method :some_data
end
#app/views/institutions/index.html
<h1></h1>
<%= my_view_method(some_data) %>
那么从我的 gem 添加方法到 Rails MVC 的最佳方法是什么?
最佳答案
在 lib/my_gem.rb
中,您可以使用文档不足的 ActiveSupport#on_load ,例如
require 'my_gem/view_helpers'
require 'my_gem/active_record'
require 'my_gem/controller_additions'
ActiveSupport.on_load(:action_view) do
include MyGem::ViewHelpers
end
ActiveSupport.on_load(:active_record) do
extend MyGem::ActiveRecord
end
ActiveSupport.on_load(:action_controller) do
extend MyGem::ControllerAdditions
end
In this blog post , Yehuda Katz 谈到了更多关于周围环境的事情。这对您来说也可能是一本有趣的读物!
关于ruby - 向 Rails 4 MVC 添加自定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20514222/