---
title: "优秀rails代码赏析"
author: "pingfeng"
date: "2011-03-18T16:12:48Z"
tags: []
categories: ["编程语言"]
slug: "rails"
draft: false
lastmod: "2011-05-27T17:02:53Z"
id: 966685
url: "https://pingfeng.iteye.com/blog/966685"
---

扔掉mfc的那些register函数（太丑了！），继承即是注册，还带配置：

 

```
  class Railtie

   class << self
      def subclasses
        @subclasses ||= []
      end

      def inherited(base)
        unless base.abstract_railtie?
          base.send(:include, self::Configurable)
          subclasses << base
        end
      end
  end
end

#mongoid,用tap就像unix的tap   
    def as_document
      attributes = raw_attributes
      attributes.tap do |attrs|
        relations.select { |name, meta| meta.embedded? }.each do |name, meta|
          relation = send(name, false, :continue => false)
          attrs[name] = relation.as_document unless relation.blank?
        end
      end


 ＃[self.name, @@under_path, const_name.to_s, path].compact.join("::") 
＃ 这种写法可以有效的去除 path， @@uner_path是否为空的判断！


 def autoload(const_name, path = @@at_path)
      full = [self.name, @@under_path, const_name.to_s, path].compact.join("::")
      location = path || Inflector.underscore(full)

      if @@eager_autoload
        @@autoloads[const_name] = location
      end
      super const_name, location
    end

```