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

13 篇文章 0 订阅

在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
   end
end

class B  < A[5.1]
end

其实就是这样的简单!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值