本文根据 Devhints / Rails plugins 翻译。代码示例及版本范围沿用原文。
生成插件
生成 Rails 引擎 (Engine) 插件:
rails plugin new myplugin --skip-bundle --full
初始化程序 (Initializers)
初始化程序 (Initializers)
初始化方法
继承 Railtie 并提供一个 initializer 方法。
module NewPlugin
class Railtie < Rails::Railtie
initializer "newplugin.initialize" do |app|
# subscribe to all rails notifications: controllers, AR, etc.
ActiveSupport::Notifications.subscribe do |*args|
event = ActiveSupport::Notifications::Event.new(*args)
puts "Got notification: #{event.inspect}"
end
end
end
end
自定义路由
自定义路由
创建路由
若要创建自定义 routes.rb 关键字:
# # routes.rb:
# myplugin_for x
#
class ActionDispatch::Routing
class Mapper
def myplugin_for(*x)
end
end
end
使用代码块 (block) 的示例:
# authenticated do
# resources :users
# end
#
def authenticated
constraint = lambda { |request| request... }
constraints(constraint) { yield }
end
自定义生成器 (Generators)
自定义生成器 (Generators)
基础
# rails g initializer
# lib/generators/initializer_generator.rb
class InitializerGenerator < Rails::Generators::Base
def create_initializer_file
create_file "config/initializers/initializer.rb", "# Add initialization content here"
end
end
- 扩展
Rails::Generators::Base. - 当调用生成器时,其中的每个公有 (public) 方法都会被执行。
生成一个生成器
$ rails generate generator initializer
NamedBase
使用 NamedBase 如果需要接收参数,请改用它。它可作为以下内容使用:
file_name.
class InitializerGenerator < Rails::Generators::Base
def lol
puts file_name
end
end
更多
class InitializerGenerator < Rails::Generators::NamedBase
#
source_root File.expand_path("../templates", __FILE__)
desc "Description goes here."
end
生成器(Generators)查找
调用时 rails g XXX:
[rails/]generators/XXX/XXX_generator.rb
[rails/]generators/XXX_generator.rb
调用时 rails g XXX:YYY:
[rails/]generators/XXX/YYY_generator.rb
ActiveModel 的“acts as”功能
acts as
# yaffle/lib/yaffle/acts_as_yaffle.rb
module Yaffle
module ActsAsYaffle
extend ActiveSupport::Concern
included do
end
module ClassMethods
def acts_as_yaffle(options = {})
# your code will go here
end
end
end
end
ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle