rails3.1 新特性

Posted by wxianfeng Wed, 02 Mar 2011 02:59:00 GMT

目前 rails的稳定版本是 rails3.0.5,但是rails3.1的新特性已经出来了 , 来看看 。。。

1,Scopes

rails 3.0 我们使用scope,常这样使用:

class Product < ActiveRecord::Base
  scope :nokia, lambda {
    where(:name => 'Nokia')
  }
  scope :category, lambda { |value|
    where(:category => value)
  }
  scope :combined, lambda { |value|
    nokia.category(value)
  }
end
$ @nokia = Product.nokia.all # to get all the products with name Nokia
$ Product.category("Mobile").all # to get all the products with category Mobile
$ Product.nokia.category("Mobile").all #Combined : to get all the products with name = Nokia and category = Mobile

发现scope 只能使用在一个Class中,那么有多个Class 怎么办,rails 3.1 你可以创建一个类 作为 通用的 filter

class Filter < Struct.new(:klass)
  def call(*args); end
end

module NameFilter
  def call(*args)
    klass.where(:name => args.shift)
    super(*args)
  end
end

module CategoryFilter
  def call(category, *args)
    klass.where(:category => args.shift)
    super(*args)
  end
end

class Product < ActiveRecord::Base
  scope :combined, Filter.new(self).extend(CategoryFilter).extend(NameFilter)
end

class User < ActiveRecord::Base
  scope :combined, Filter.new(self).extend(CategoryFilter).extend(NameFilter)
end

Product.combined('Nokia','Mobile').all
User.combined('John','Manager').all

2,Automatic Flushing

Automatic Flushing 是改善性能的一项技术,例如 之前rails渲染页面的机理是这样的,第一步 rails 生成 静态页面 ,例如css,图片,js文件 ,页面html ,然后在一个一个的下载

添加了 Automatic Flushing 这个技术后 ,将会 大大提高性能 , 服务器端一边 生成静态文件 ,浏览器一边就下载了 ,改善了用户体验 和性能

3,css sprites(图片拼合)

rails 3.1 默认支持 icons sprite , 多个icon放在一张图片上 ,显示icon通过css来控制,这样有利于减少http请求数

4,js,css文件可以放到views 下面

#Preprocess:
app/views/js/item.js.erb
app/views/css/style.css.erb
#This code will be compiled to the files like this:
#Compiles:
public/application.js
public/style.css

5,一些旧的用法将不被支持,例如 :conditions

旧的写法:

class User
  scope :name, :conditions => { :name => 'David' }
  scope :age, lambda {|age| {:conditions => ["age > ?", age] }}
end

新的写法:

class User
  scope :name, where(:name => 'David')
  scope :age, lambda {|age| where("age > ?", age) }
end

SEE:

http://hemju.com/2011/02/23/rails-3-1-release-rumors-and-news-about-features/

This entry was posted on Wed, 02 Mar 2011 02:59:00 GMT and Posted in . You can follow any any response to this entry through the Atom feed. You can leave a comment or a trackback from your own site.

Tags


Trackbacks

Use the following link to trackback from your own site:
http://wxianfeng.com/trackbacks?article_id=184

  1. league of angels hack league of angels hack
    rails3.1 新特性 | 0x64

Comments

  1. Avatar
    up2u0609 {{count}} months ago:

    scope那个是ruby的做法,那个Filter类只是模拟了一个lambda,跟rials没什么关系。
    不过还是很有意思。

  2. Avatar
    wxianfeng over {{count}} years ago:

    @up2u0609

    是的

Leave a comment