[ROR] rails migration 中继承 ActiveRecord::Migration[5.1] 带版本号实现原理

来源:互联网 发布:己知直径求周长 编辑:程序博客网 时间:2024/06/10 07:23

在Rilas5 以后 

migration文件中的一般继承都会带有版本号,初看是正常的,可是如果自己写的话就会报错,这种写法本身Ruby是不支持的

譬如:

class A[5.1]

end

这种写法本身就是错误的,我是比较迟钝的,也没有反应过来这rails到底是这么实现的 于是我就去看了源码,

源码的实现方式是:

    class Current < Migration # :nodoc:    end    def self.inherited(subclass) # :nodoc:      super      if subclass.superclass == Migration        raise StandardError, "Directly inheriting from ActiveRecord::Migration is not supported. " \          "Please specify the Rails release the migration was written for:\n" \          "\n" \          "  class #{subclass} < ActiveRecord::Migration[4.2]"      end    end    def self.[](version)      Compatibility.find(version)    end    def self.current_version      ActiveRecord::VERSION::STRING.to_f    end
看到这段代码的时候真的是 恍然大悟!

只能感慨 Ruby 就是这样一个神奇的语言! 真的 是 Magic

实现带有版本的原理其实真的很简答,

class  A  def self.[] version      self   endendclass B  < A[5.1]end

其实就是这样的简单!

原创粉丝点击