诗歌rails之如何写一个简单的Rails Plugin

生成plugin骨架代码:
Ruby代码
  1. ruby script\generate plugin MyPlugin  
功能需求:
在BlogController中把所有符合条件的Post(Model)生成为xml
如果不使用插件,很easy :
in BlogController
Ruby代码
  1. def export_to_xml  
  2.   posts = Post.find(:all:order => 'published_date',  
  3.       :conditions => ['title = ?''love'])  
  4.   send_data posts.to_xml, :type => 'text/xml; charset=UTF-8;',  
  5.       :disposition => "attachment; filename=posts.xml"  
  6. end  

如果使用插件,我们要求能这样:
Ruby代码
  1. class BlogController < ApplicationController  
  2.   my_plugin :post  
  3.     
  4.   def to_xml  
  5.     export_to_xml  
  6.   end  
  7. end  

OK,立刻满足以上的要求,进入你的project:
生成plugin
Ruby代码
  1. ruby script\generate plugin MyPlugin  
and than to find:
vendor/plugins/my_plugin/lib/my_plugin.rb
接着就是edit了:
Ruby代码
  1. module MyPlugin  
  2.     
  3.   def self.included(base)  
  4.     base.extend(ClassMethods)  
  5.   end  
  6.   
  7.   class Config  
  8.     attr_reader :model  
  9.     attr_reader :model_id  
  10.       
  11.     def initialize(model_id)  
  12.       @model_id = model_id  
  13.       @model = model_id.to_s.camelize.constantize  
  14.     end  
  15.       
  16.     def model_name  
  17.       @model_id.to_s  
  18.     end  
  19.   end  
  20.     
  21.   module ClassMethods  
  22.       
  23.     def my_plugin(model_id = nil)  
  24.       model_id = self.to_s.split('::').last.sub(/Controller$/, '').pluralize.singularize.underscore unless model_id  
  25.       @my_plugin_config = MyPlugin::Config.new(model_id)  
  26.       include MyPlugin::InstanceMethods  
  27.     end  
  28.       
  29.     def my_plugin_config  
  30.       @my_plugin_config || self.superclass.instance_variable_get('@my_plugin_config')  
  31.     end  
  32.       
  33.   end  
  34.   
  35.   module InstanceMethods  
  36.       
  37.     def export_to_xml  
  38.       data = self.class.my_plugin_config.model.find(:all:order => 'published_date':conditions => conditions_for_collection)  
  39.       send_data data.to_xml, :type => 'text/xml; charset=UTF-8;',  
  40.         :disposition => "attachment; filename=#{self.class.my_plugin_config.model_name.pluralize}.xml"  
  41.     end  
  42.       
  43.     # 在controller中覆盖此method,写入满足的条件  
  44.     def conditions_for_collection  
  45.     end  
  46.       
  47.   end  
  48.   
  49. end  


OK了吗? No No No 还要让rails加载plugin,在rails应用启动时,会到vendor/plugins目录查找所有plugin,并执行其中的init.rb
那么就edit init.rb
Ruby代码
  1. ActionController::Base.class_eval do  
  2.   include MyPlugin  
  3. end  

或edit这样:
Ruby代码
  1. require 'my_plugin'  
  2. ActionController::Base.send :include, MyPlugin  


最后就按上面的需求写入controller了
posted @ 2009-08-20 11:31  麦飞  阅读(474)  评论(0编辑  收藏  举报