ruby-on-rails - Ruby 挑战 - 方法链和惰性求值

标签 ruby-on-rails ruby lazy-evaluation method-chaining

看完文章http://jeffkreeftmeijer.com/2011/method-chaining-and-lazy-evaluation-in-ruby/ ,我开始寻找更好的方法链和惰性求值解决方案。

我想我已经用以下五个规范概括了核心问题;谁能让他们全部通过?

任何事情都可以:子类化、委托(delegate)、元编程,但不鼓励后者。

最好将依赖性保持在最低限度:

require 'rspec'

class Foo
    # Epic code here
end

describe Foo do

  it 'should return an array corresponding to the reverse of the method chain' do
    # Why the reverse? So that we're forced to evaluate something
    Foo.bar.baz.should == ['baz', 'bar']
    Foo.baz.bar.should == ['bar', 'baz']
  end

  it 'should be able to chain a new method after initial evaluation' do
    foobar = Foo.bar
    foobar.baz.should == ['baz', 'bar']

    foobaz = Foo.baz
    foobaz.bar.should == ['bar', 'baz']
  end

  it 'should not mutate instance data on method calls' do
    foobar = Foo.bar
    foobar.baz
    foobar.baz.should == ['baz', 'bar']
  end

  it 'should behave as an array as much as possible' do
    Foo.bar.baz.map(&:upcase).should == ['BAZ', 'BAR']

    Foo.baz.bar.join.should == 'barbaz'

    Foo.bar.baz.inject do |acc, str|
      acc << acc << str
    end.should == 'bazbazbar'

    # === There will be cake! ===
    # Foo.ancestors.should include Array
    # Foo.new.should == []
    # Foo.new.methods.should_not include 'method_missing'
  end

  it "should be a general solution to the problem I'm hoping to solve" do
    Foo.bar.baz.quux.rab.zab.xuuq.should == ['xuuq', 'zab', 'rab', 'quux', 'baz', 'bar']
    Foo.xuuq.zab.rab.quux.baz.bar.should == ['bar', 'baz', 'quux', 'rab', 'zab', 'xuuq']
    foobarbaz = Foo.bar.baz
    foobarbazquux = foobarbaz.quux
    foobarbazquuxxuuq = foobarbazquux.xuuq
    foobarbazquuxzab = foobarbazquux.zab

    foobarbaz.should == ['baz', 'bar']
    foobarbazquux.should == ['quux', 'baz', 'bar']
    foobarbazquuxxuuq.should == ['xuuq', 'quux', 'baz', 'bar']
    foobarbazquuxzab.should == ['zab', 'quux', 'baz', 'bar']
  end

end

最佳答案

这受到 Amadan 的回答的启发,但使用的代码行数更少:

class Foo < Array
    def self.method_missing(message, *args)
        new 1, message.to_s
    end
    def method_missing(message, *args)
        dup.unshift message.to_s
    end
end

关于ruby-on-rails - Ruby 挑战 - 方法链和惰性求值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8632702/

相关文章:

ruby-on-rails - 如何在 Rails 中使用语言环境作为参数重定向?

ruby-on-rails - 在 El Capitan 上安装 Nokogiri (1.6.7) 时出错

ruby-on-rails - Ruby on Rails URL 中的资源映射(RESTful API)

ruby-on-rails - unicorn 服务 Upstart 脚本抛出 "-su: bundle: command not found"

ruby-on-rails - 检索数据库数据的 finder 方法的性能

ruby CSV : ignoring empty column

ruby-on-rails - 从 ActiveRecord 对象中提取两个属性的快捷方式?

.net - Lazy.Force() 和 Lazy.Value 有什么区别

haskell - thunk 使用多少内存?

Scala 的 Stream 和 StackOverflowError