如何給Rails 寫插件

阅读更多

很簡單。備忘。

1 生成代碼   script/generate plugin plugin_name

2 init.rb 在運行rails前會載入,並會自動載入lib下的文件

3 寫你自己需要hook的東西

 

關鍵:如何讓rails能在controller或view裡面使用自己寫的東西

這裡就不需要在使用時候include file 了。

方法一: 在 init.rb 中添加

 

ActionView::Base.send :include, UrlEnhancerHelper
 

 

意思是吧 UrlEnhancerHelper 這個 module 包含在 ActionView::Base 裡面 。

當然這種語法也可以在自己需要的地方添加。

 

方法二:

module ActsAsExportable
  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 acts_as_exportable(model_id = nil)
      # converts Foo::BarController to 'bar' and FooBarsController to 'foo_bar'
      # and AddressController to 'address'
      model_id = self.to_s.split('::').last.sub(/Controller$/, '').\
 pluralize.singularize.underscore unless model_id
 
      @acts_as_exportable_config = ActsAsExportable::Config.new(model_id)
      include ActsAsExportable::InstanceMethods
    end
 
    # Make the @acts_as_exportable_config class variable easily
    # accessable from the instance methods.
    def acts_as_exportable_config
      @acts_as_exportable_config || self.superclass.\
 instance_variable_get('@acts_as_exportable_config')
    end
  end
 
	module InstanceMethods
	  def export_to_xml
	    data = self.class.acts_as_exportable_config.model.find(:all,
              :order => 'title',
              :conditions => conditions_for_collection)
	    send_data data.to_xml,
	      :type => 'text/xml; charset=UTF-8;',
	      :disposition => "attachment; filename=\
 #{self.class.acts_as_exportable_config.model_name.pluralize}.xml"
	  end
 
	  # Empty conditions. You can override this in your controller
    def	conditions_for_collection
    end
  end
end

 

最後是常用函數

動態定義函數:

define_methods  "name" , block

write_attribute

read_attribute

instance_variable_set

instance_variable_get

 

How to write a Rails Plugin(controller)

你可能感兴趣的:(Rails,XML)