通过优化添加的方法在Rails控制器中不可见

时间:2018-08-02 16:13:57

标签: ruby-on-rails ruby refinements

我已经如下改进了Rails控制器中的Enumerable模块,并据我所知添加了一种方法,该方法在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

0 个答案:

没有答案