Enumerate_it gem类方法中的奇怪代码

时间:2016-03-09 10:58:34

标签: ruby-on-rails ruby enums

我偶然发现了enumerate_it gem中的奇怪代码:

module EnumerateIt
  module ClassMethods
    def has_enumeration_for(attribute, options = {})
      self.enumerations = self.enumerations.dup
      ...
    end
end

对我来说似乎毫无意义,但我确信宝石开发者有理由写这个。 使用这样的作业的原因是什么?

1 个答案:

答案 0 :(得分:3)

噢,代码考古学!幸运的是,这是一个开源项目,因此我们可以访问代码的历史记录,并且 - 希望 - 更改的原因(如提交消息中所述)。

有问题的代码:

self.enumerations = self.enumerations.dup

最初是在commit 04bec59407bf14d3ab219c4b505ef1fbfce0c398中添加的,它有一个非常好的提交消息,解释了为什么添加它:

  

尊重子类

上的超类枚举      

以前,这就是行为:

class Unico::Person
  has_enumeration_for :gender
end

class Person < Unico::Person
end

Unico::Person.enumerations
# => {:gender => Gender}

Person.enumerations
# => {}
     

在此提交之后,子类将继承超类枚举:

class Unico::Person
  has_enumeration_for :gender
end

class Person < Unico::Person
end

Unico::Person.enumerations
# => {:gender => Gender}

Person.enumerations
# => {:gender => Gender}

如何找到

查看存储库的副本:

$ git clone https://github.com/cassiomarques/enumerate_it.git
Cloning into 'enumerate_it'...
remote: Counting objects: 995, done.
remote: Total 995 (delta 0), reused 0 (delta 0), pack-reused 995
Receiving objects: 100% (995/995), 178.90 KiB | 0 bytes/s, done.
Resolving deltas: 100% (474/474), done.
Checking connectivity... done.
$ cd enumerate_it

现在,让我们找到包含相关代码的所有提交:

$ git log -S "self.enumerations = self.enumerations.dup"
commit c99a15c31d156464b1139533d4377331b6e21fff
Author: Cássio Marques <cassio.marques@baby.com.br>
Date:   Thu Nov 8 17:16:36 2012 -0200

    We should extend the EnumerateIt module instead of including it, since the has_enumeration_for is a class method

commit 04bec59407bf14d3ab219c4b505ef1fbfce0c398
Author: Gabriel Sobrinho <gabriel.sobrinho@gmail.com>
Date:   Thu May 31 11:08:57 2012 -0300

    Respect superclass enumerations on subclasses

    Previously, this was the behavior:

      class Unico::Person
        has_enumeration_for :gender
      end

      class Person < Unico::Person
      end

      Unico::Person.enumerations
      # => {:gender => Gender}

      Person.enumerations
      # => {}

    After this commit, subclasses will inherit the superclass enumerations:

      class Unico::Person
        has_enumeration_for :gender
      end

      class Person < Unico::Person
      end

      Unico::Person.enumerations
      # => {:gender => Gender}

      Person.enumerations
      # => {:gender => Gender}

仔细观察git show的提交,发现最顶层的代码只是将代码从一个地方移动到另一个地方,而后一个提交实际上添加了代码。

这就是我们想要的提交。