Active Record的設(shè)計

自動加載機制
require "active_support"
require "active_support/rails"
require "active_model"
require "arel"
require "yaml"

require "active_record/version"
require "active_model/attribute_set"

module ActiveRecord
  extend ActiveSupport::Autoload

  autoload :Base
  autoload :Callbacks
  autoload :Core
  autoload :ConnectionHandling
  autoload :CounterCache
  autoload :DynamicMatchers
  autoload :Enum
  autoload :InternalMetadata
  autoload :Explain
  autoload :Inheritance
  autoload :Integration
  autoload :Migration
  autoload :Migrator, "active_record/migration"
  autoload :ModelSchema
  autoload :NestedAttributes
  autoload :NoTouching
  autoload :TouchLater
  autoload :Persistence
  autoload :QueryCache
  autoload :Querying
  autoload :CollectionCacheKey
  autoload :ReadonlyAttributes
  autoload :RecordInvalid, "active_record/validations"
  autoload :Reflection
  autoload :RuntimeRegistry
  autoload :Sanitization
  autoload :Schema
  autoload :SchemaDumper
  autoload :SchemaMigration
  autoload :Scoping
  autoload :Serialization
  autoload :StatementCache
  autoload :Store
  autoload :Suppressor
  autoload :Timestamp
  autoload :Transactions
  autoload :Translation
  autoload :Validations
  autoload :SecureToken

  eager_autoload do
    autoload :ActiveRecordError, "active_record/errors"
    autoload :ConnectionNotEstablished, "active_record/errors"
    autoload :ConnectionAdapters, "active_record/connection_adapters/abstract_adapter"

    autoload :Aggregations
    autoload :Associations
    autoload :AttributeAssignment
    autoload :AttributeMethods
    autoload :AutosaveAssociation

    autoload :LegacyYamlAdapter

    autoload :Relation
    autoload :AssociationRelation
    autoload :NullRelation

    autoload_under "relation" do
      autoload :QueryMethods
      autoload :FinderMethods
      autoload :Calculations
      autoload :PredicateBuilder
      autoload :SpawnMethods
      autoload :Batches
      autoload :Delegation
    end

    autoload :Result
    autoload :TableMetadata
    autoload :Type
  end

  module Coders
    autoload :YAMLColumn, "active_record/coders/yaml_column"
    autoload :JSON, "active_record/coders/json"
  end

  module AttributeMethods
    extend ActiveSupport::Autoload

    eager_autoload do
      autoload :BeforeTypeCast
      autoload :Dirty
      autoload :PrimaryKey
      autoload :Query
      autoload :Read
      autoload :TimeZoneConversion
      autoload :Write
      autoload :Serialization
    end
  end

  module Locking
    extend ActiveSupport::Autoload

    eager_autoload do
      autoload :Optimistic
      autoload :Pessimistic
    end
  end

  module ConnectionAdapters
    extend ActiveSupport::Autoload

    eager_autoload do
      autoload :AbstractAdapter
    end
  end

  module Scoping
    extend ActiveSupport::Autoload

    eager_autoload do
      autoload :Named
      autoload :Default
    end
  end

  module Tasks
    extend ActiveSupport::Autoload

    autoload :DatabaseTasks
    autoload :SQLiteDatabaseTasks, "active_record/tasks/sqlite_database_tasks"
    autoload :MySQLDatabaseTasks,  "active_record/tasks/mysql_database_tasks"
    autoload :PostgreSQLDatabaseTasks,
      "active_record/tasks/postgresql_database_tasks"
  end

  autoload :TestFixtures, "active_record/fixtures"

  def self.eager_load!
    super
    ActiveRecord::Locking.eager_load!
    ActiveRecord::Scoping.eager_load!
    ActiveRecord::Associations.eager_load!
    ActiveRecord::AttributeMethods.eager_load!
    ActiveRecord::ConnectionAdapters.eager_load!
  end
end

ActiveSupport.on_load(:active_record) do
  Arel::Table.engine = self
end

ActiveSupport.on_load(:i18n) do
  I18n.load_path << File.expand_path("active_record/locale/en.yml", __dir__)
end

YAML.load_tags["!ruby/object:ActiveRecord::AttributeSet"] = "ActiveModel::AttributeSet"
YAML.load_tags["!ruby/object:ActiveRecord::Attribute::FromDatabase"] = "ActiveModel::Attribute::FromDatabase"
YAML.load_tags["!ruby/object:ActiveRecord::LazyAttributeHash"] = "ActiveModel::LazyAttributeHash"

Active Record是Rails的ORM功能實現(xiàn)涂身。上面代碼使用了ActiveSupport::Autoload模塊裸扶,該模塊定義了autoload方法左驾。代碼首次引用模塊時允坚,這個方法通過命名約定自動識別和加載該模塊匹层。
我們先看下Autoload模塊代碼的具體實現(xiàn):

# frozen_string_literal: true

require "active_support/inflector/methods"

module ActiveSupport
  # Autoload and eager load conveniences for your library.
  #
  # This module allows you to define autoloads based on
  # Rails conventions (i.e. no need to define the path
  # it is automatically guessed based on the filename)
  # and also define a set of constants that needs to be
  # eager loaded:
  #
  #   module MyLib
  #     extend ActiveSupport::Autoload
  #
  #     autoload :Model
  #
  #     eager_autoload do
  #       autoload :Cache
  #     end
  #   end
  #
  # Then your library can be eager loaded by simply calling:
  #
  #   MyLib.eager_load!
  module Autoload
    def self.extended(base) # :nodoc:
      base.class_eval do
        @_autoloads = {}
        @_under_path = nil
        @_at_path = nil
        @_eager_autoload = false
      end
    end

    def autoload(const_name, path = @_at_path)
      unless path
        full = [name, @_under_path, const_name.to_s].compact.join("::")
        path = Inflector.underscore(full)
      end

      if @_eager_autoload
        @_autoloads[const_name] = path
      end

      super const_name, path
    end

    def autoload_under(path)
      @_under_path, old_path = path, @_under_path
      yield
    ensure
      @_under_path = old_path
    end

    def autoload_at(path)
      @_at_path, old_path = path, @_at_path
      yield
    ensure
      @_at_path = old_path
    end

    def eager_autoload
      old_eager, @_eager_autoload = @_eager_autoload, true
      yield
    ensure
      @_eager_autoload = old_eager
    end

    def eager_load!
      @_autoloads.each_value { |file| require file }
    end

    def autoloads
      @_autoloads
    end
  end
end

首先看到autoload方法隙笆,如果再沒有傳path參數(shù)的情況下,autoload會根據(jù)當(dāng)前的類(模塊)名升筏,和傳入的const_name,組成一個path仲器,最后根據(jù)傳入的const_name,和path,調(diào)用ruby原生的autoload加載模塊仰冠。如果通過傳遞block的方式調(diào)用eager_autoload,這種情況下調(diào)用autoload,會把相應(yīng)的模塊加入到@_eager_autoload中蝶糯,然后可以通過eager_load!方法直接require對應(yīng)path下的文件洋只。以及相應(yīng)的autoload_at和autoload_under,也可以通過block的方式傳遞path昼捍,改變默認(rèn)的@_at_path,執(zhí)行autoload识虚,真的是非常巧妙的方式。
ruby原生的autoload部分妒茬,參考:http://www.reibang.com/p/d9dcbed59a82

Validations模塊

ActiveRecord::Base包含了 ActiveRecord::Validations模塊担锤,里面卻找不到我們要用的validate方法。這個模塊來自Active Model乍钻,Active Record的一個依賴庫肛循。為什么作者要把validate方法定義在別的庫呢,其實早期的rails沒有Active Model庫银择,那時候validate方法定義在Active Record里多糠,但是隨著Active Record的不斷壯大,開發(fā)者發(fā)現(xiàn)其實這是兩項獨立的工作浩考,一項與數(shù)據(jù)庫操作相關(guān)夹孔,比如保存和加載數(shù)據(jù)庫。但另一項是處理對象模型的析孽,比如維護對象屬性搭伤,或者跟蹤對象屬性的有效性。于是就被分成了兩個庫袜瞬。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末怜俐,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子吞滞,更是在濱河造成了極大的恐慌佑菩,老刑警劉巖盾沫,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異殿漠,居然都是意外死亡赴精,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進店門绞幌,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蕾哟,“玉大人,你說我怎么就攤上這事莲蜘√啡罚” “怎么了?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵票渠,是天一觀的道長逐哈。 經(jīng)常有香客問我,道長问顷,這世上最難降的妖魔是什么昂秃? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮杜窄,結(jié)果婚禮上肠骆,老公的妹妹穿的比我還像新娘。我一直安慰自己塞耕,他們只是感情好蚀腿,可當(dāng)我...
    茶點故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著扫外,像睡著了一般莉钙。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上筛谚,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天胆胰,我揣著相機與錄音,去河邊找鬼刻获。 笑死蜀涨,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的蝎毡。 我是一名探鬼主播厚柳,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼沐兵!你這毒婦竟也來了别垮?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤扎谎,失蹤者是張志新(化名)和其女友劉穎碳想,沒想到半個月后烧董,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡胧奔,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年逊移,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片龙填。...
    茶點故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡胳泉,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出岩遗,到底是詐尸還是另有隱情扇商,我是刑警寧澤,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布宿礁,位于F島的核電站案铺,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏梆靖。R本人自食惡果不足惜红且,卻給世界環(huán)境...
    茶點故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望涤姊。 院中可真熱鬧,春花似錦嗤放、人聲如沸思喊。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽恨课。三九已至,卻和暖如春岳服,著一層夾襖步出監(jiān)牢的瞬間剂公,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工吊宋, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留纲辽,地道東北人。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓璃搜,卻偏偏與公主長得像拖吼,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子这吻,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,979評論 2 355

推薦閱讀更多精彩內(nèi)容