Rails丰富的插件真是强大,幻想着把各个功能都做出插件,以后开发系统就像搭积木一样堆积就好啦,呵呵。
开发个Rails插件其实不难,或者说很简单,流程基本如下:
1、生成骨架
在Rails的script下有个generate,可以直接生成骨架,执行:
# ruby script/generate plugin foo
就会在$RAILS_ROOT/vendor/plugins下生成一个foo目录,如下:
Ruby代码
- /1stlog$ruby script/generate plugin foo
- create vendor/plugins/foo/lib
- create vendor/plugins/foo/tasks
- create vendor/plugins/foo/test
- create vendor/plugins/foo/README
- create vendor/plugins/foo/MIT-LICENSE
- create vendor/plugins/foo/Rakefile
- create vendor/plugins/foo/init.rb
- create vendor/plugins/foo/install.rb
- create vendor/plugins/foo/uninstall.rb
- create vendor/plugins/foo/lib/foo.rb
- create vendor/plugins/foo/tasks/foo_tasks.rake
- create vendor/plugins/foo/test/foo_test.rb
2、编写相关代码
在lib/foo.rb 下编写你的插件代码即可。
Ruby代码
-
在lib/foo.rb 下编写你的插件代码即可。
Ruby代码- module Foo
- def say_hello name
- “hello #{name}”
- end
- end
3、混入到core中去
在init.rb中编写混入代码即可。Ruby代码- require ‘foo’
- ActionController::Base.send :include, Foo