【译】公用方法提取到模块中

Sunday, July 25, 2010

原文:http://rails-bestpractices.com/posts/17-extract-into-module

一些代码和我们的模型都有关系,他们负责做一些公用的事情, 比如记日志和授权, 我们可以把这些代码提取到模块中并且重用他们

丑陋的...

class User < ActiveRecord::Base
  validates_presence_of :cellphone
  before_save :parse_cellphone

def parse_cellphone
    # do something
  end
end

在这个例子中, 用户模型中有个validates_presence_of :cellphone的校验和一个
before_save的回调,我们可以把它抽象出来放到模块中

重用...

module HasCellphone
  def self.included(base)
    base.validates_presence_of :cellphone
    base.before_save :parse_cellphone
  end

def parse_cellphone
    # do something
  end
end



class User < ActiveRecord::Base
  include HasCellphone
end

现在我们把和cellphone相关的验证和回调提取到了HasCellphone这个模块中, 这样我们只要在需要用到的模型中include
HasCellphone 这个模块就可以了

This entry was tagged Rails and Best-Practices

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top