如何写一个简单的Rails Plugin

rails plugin是什么,自己google吧 :wink:
生成plugin骨架代码:
ruby script\generate plugin MyPlugin


功能需求:
在BlogController中把所有符合条件的Post(Model)生成为xml
如果不使用插件,很easy :
in BlogController

def export_to_xml
posts = Post.find(:all, :order => 'published_date',
:conditions => ['title = ?', 'love'])
send_data posts.to_xml, :type => 'text/xml; charset=UTF-8;',
:disposition => "attachment; filename=posts.xml"
end

如果使用插件,我们要求能这样:

class BlogController < ApplicationController
my_plugin :post

def to_xml
export_to_xml
end
end


OK,立刻满足以上的要求,进入你的project:
生成plugin
ruby script\generate plugin MyPlugin

and than to find:
vendor/plugins/my_plugin/lib/my_plugin.rb
接着就是edit了:

module MyPlugin

def self.included(base)
base.extend(ClassMethods)
end

class Config
attr_reader :model
attr_reader :model_id

def initialize(model_id)
@model_id = model_id
@model = model_id.to_s.camelize.constantize
end

def model_name
@model_id.to_s
end
end

module ClassMethods

def my_plugin(model_id = nil)
model_id = self.to_s.split('::').last.sub(/Controller$/, '').pluralize.singularize.underscore unless model_id
@my_plugin_config = MyPlugin::Config.new(model_id)
include MyPlugin::InstanceMethods
end

def my_plugin_config
@my_plugin_config || self.superclass.instance_variable_get('@my_plugin_config')
end

end

module InstanceMethods

def export_to_xml
data = self.class.my_plugin_config.model.find(:all, :order => 'published_date', :conditions => conditions_for_collection)
send_data data.to_xml, :type => 'text/xml; charset=UTF-8;',
:disposition => "attachment; filename=#{self.class.my_plugin_config.model_name.pluralize}.xml"
end

# 在controller中覆盖此method,写入满足的条件
def conditions_for_collection
end

end

end


OK了吗? No No No 还要让rails加载plugin,在rails应用启动时,会到vendor/plugins目录查找所有plugin,并执行其中的init.rb
那么就edit init.rb

ActionController::Base.class_eval do
include MyPlugin
end

或edit这样:

require 'my_plugin'
ActionController::Base.send :include, MyPlugin


最后就按上面的需求写入controller了 :arrow:
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯智能台灯

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值