1

Enumerable在 Rails 控制器中改进了模块,如下所示,添加了一种方法,据我所知,Rails 或标准库中尚不存在该方法:

module OrderedGroupBy
  refine Enumerable do
    def ordered_group_by(&block)
      items = each
      groups = []
      prev = nil
      loop do
        begin
          i = items.next
          current = i.instance_eval(&block)
          groups << [] if current != prev
          prev = current
          groups.last << i
        rescue StopIteration
          break
        end
      end
      groups
    end
  end
end

using OrderedGroupBy

class TestController < ApplicationController
  def test
    numbers = ['one', 'three', 'seven', 'four', 'nine']
    @groups = numbers.ordered_group_by(&:length)
  end
end

调用控制器操作test会导致NoMethodError

undefined method `ordered_group_by' for ["one", "three", "seven", "four", "nine"]:Array

为了缩小问题范围,我创建了一个具有相同结构的独立文件(没有 Rails 环境):

module OrderedGroupBy
  refine Enumerable do
    def ordered_group_by(&block)
      items = each
      groups = []
      prev = nil
      loop do
        begin
          i = items.next
          current = i.instance_eval(&block)
          groups << [] if current != prev
          prev = current
          groups.last << i
        rescue StopIteration
          break
        end
      end
      groups
    end
  end
end

using OrderedGroupBy

class TestController < Object
  def test
    numbers = ['one', 'three', 'seven', 'four', 'nine']
    @groups = numbers.ordered_group_by(&:length)
  end
end

TestController.new.test

在这种情况下,调用测试方法会得到预期的结果:

# => [["one"], ["three", "seven"], ["four", "nine"]]

另外,如果我直接在 Enumerable 上定义了 ordered_group_by 方法,而不使用refine,我可以成功调用该方法。

有什么原因导致这在 Rails 的上下文中不能作为改进工作,还是我还缺少其他东西?

编辑:我使用的是 rails 5.2.0,这是一个空项目,只有rails new _并且rails generate controller Test test已经运行。

4

0 回答 0