`
jsntghf
  • 浏览: 2481695 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

Rails2.2新方法试用

阅读更多

Rails2.2的ActiveSupport新增加了几个方法,非常有意思。在此列举其中的两个:StringInquirer和many?进行试用。

 

一、StringInquirer


有时候,我们有这样的需求,看一个用户是否是激活状态,数据是从数据库里查出来的:

 

user = User.find(params[:id])
user.status  # => "active"
user.status == "active"  # => true
user.status == "inactive"  # => false

 

现在我们有了更好的方法:

 

class User
  def status
    ActiveSupport::StringInquirer.new("#{self.status}")
  end
end

user = User.find(params[:id])
user.status  # => "active"
user.status.active?  # => true
user.status.inactive?  # => false
user.status.xxx?  # => false

 

二、many?

 

Enumerable模块里添加了一个many?方法。它和它的名字一样,它可以告诉你collection是否包括超过一个对象。
这个方法是 collection.size > 1 的别名(alias)。

 

[].many?  # => false
[ 1 ].many?  # => false
[ 1, 2 ].many?  # => true

 

除例子里的格式外,这个方法还可以接受一个block。

 

x = %w{ a b c b c }  # => ["a", "b", "c", "b", "c"]
x.many?  # => true
x.many? { |y| y == 'a' }  # => false
x.many? { |y| y == 'b' }  # => true
people.many? { |p| p.age > 26 }

 

只有block里面的元素数量超过一个时才会返回true, 如果没有block的话,当collection包含超过一个对象时才返回true。


我自己实现了一个how_many(item)方法,来计算一个数组里有几个item:

 

def how_many(item)
   return select{|y| y == item}.size
end

x = %w{ a b c b c }
x.how_many("a") # => 1
x.how_many("b") # => 2
x.how_many("c") # => 2

 

具体如何将这个方法加入模块中,可以参考http://www.iteye.com/topic/521123


非常简单,但是比较实用。

分享到:
评论
3 楼 kilik52 2009-11-29  
多谢楼上。
2 楼 yangzhihuan 2009-11-27  
楼上的,可以这样:
module ActiveRecord
  class Base
    def self.string_inquirer(prop)
      define_method prop.to_s do
        ActiveSupport::StringInquirer.new("#{self.send(prop.to_s)}")
      end
    end
  end
end


当你想用这个特性的时候,就可以:
class YourClass < ActiveRecord::Base

  string_inquirer :ooxx

end
1 楼 kilik52 2009-11-26  
如果这段:
def status  
  ActiveSupport::StringInquirer.new("#{self.status}")  
end  


能够变成:
string_inquirer :status

就好了。

相关推荐

Global site tag (gtag.js) - Google Analytics