作者:Ryan Daigle 来源:JavaEye 酷勤网收集 2008-05-23
摘要
rails的plugin机制的杰出是有很多理由的,其中一个是使用plugin可以获得额外的功能但不用依赖工程外部的东西,因为他们和你的工程是打包到一起的.但是直到最近,并没有好的方法来管理一个rails工程对gem的依赖,rails新的版本中使用了一个很好的办法来管理gem依赖
系列文章汇总《Ruby on Rails 2.1新特性》
Ryan Daigle发布了一系列关于rails2.1中新特性的文章.这里是这个系列中的一篇.
rails的plugin机制的杰出是有很多理由的,其中一个是使用plugin可以获得额外的功能但不用依赖工程外部的东西,因为他们和你的工程是打包到一起的.但是直到最近,并没有好的方法来管理一个rails工程对gem的依赖,所以我们不得不使用自己的策略.
但rails新的版本中使用了一个很好的办法来管理gem依赖,在我们的environment.rb中写下如下代码
- Rails::Initializer.run do |config|
- # Require the latest version of haml
- config.gem "haml"
- # Require a specific version of chronic
- config.gem "chronic", :version => '0.2.3'
- # Require a gem from a non-standard repo
- config.gem "hpricot", :source => "http://code.whytheluckystiff.net"
- # Require a gem that needs to require a file different than the gem's name
- # I.e. if you normally load the gem with require 'aws/s3' instead of
- # require 'aws-s3' then you would need to specify the :lib option
- config.gem "aws-s3", :lib => "aws/s3"
- end
Rails::Initializer.run do |config| # Require the latest version of haml config.gem "haml" # Require a specific version of chronic config.gem "chronic", :version => '0.2.3' # Require a gem from a non-standard repo config.gem "hpricot", :source => "http://code.whytheluckystiff.net" # Require a gem that needs to require a file different than the gem's name # I.e. if you normally load the gem with require 'aws/s3' instead of # require 'aws-s3' then you would need to specify the :lib option config.gem "aws-s3", :lib => "aws/s3" end
现在,当你的程序启动时.rails会自动找到并且require所有你列出来的gem.但是如果你的系统并没有安装所有的这些gem呢?这里有一个rake task会安装那些你你列出来的gem:
- rake gems:install
rake gems:install
当然,在运行这条命令前,你可以用rake gems这条命令来查看你的gem的依赖关系.
但是,这并没有把这些gem打包到你的工程,他只是引用系统的gem.如果你想吧他们存放到你的工程中,你可以使用这条命令:
- rake gems:unpack
rake gems:unpack
你还可以指定特定的gem来存放:
- # Unpack only the hpricot gem to vendor/gems
- rake gems:unpack GEM=hpricot
# Unpack only the hpricot gem to vendor/gems rake gems:unpack GEM=hpricot
这样就会吧gem存放到 vender/gems/hpricot-0.5,他会在启动是被自动加载.
现在你可以选择为每个environment安装所需的gem,也可以把gem存放你的代码中.
原文:http://ryandaigle.com/
来自:http://www.javaeye.com/news/2334


