Ruby EventMachine 和函数

标签 ruby redis eventmachine

我正在使用合适的 Redis EM gem(在我的例子中为“em-hiredis”)读取 EventMachine react 器循环中的 Redis 集,并且必须检查某些 Redis 集是否包含级联中的成员。我的目标是获取不为空的集合的名称:

require 'eventmachine'
require 'em-hiredis'

def fetch_queue
  @redis.scard('todo').callback do |scard_todo|
    if scard_todo.zero?
      @redis.scard('failed_1').callback do |scard_failed_1|
        if scard_failed_1.zero?
          @redis.scard('failed_2').callback do |scard_failed_2|
            if scard_failed_2.zero?
              @redis.scard('failed_3').callback do |scard_failed_3|
                if scard_failed_3.zero?
                  EM.stop
                else
                  queue = 'failed_3'
                end 
              end 
            else
              queue = 'failed_2'
            end 
          end 
        else
          queue = 'failed_1'
        end 
      end 
    else
      queue = 'todo'
    end 
  end 
end

EM.run do
  @redis = EM::Hiredis.connect "redis://#{HOST}:#{PORT}"

  # How to get the value of fetch_queue?
  foo = fetch_queue
  puts foo
end

我的问题是:如何告诉 EM 返回“fetch_queue”中“queue”的值以在 react 器循环中使用它? fetch_queue 中的简单“return queue = 'todo'”、“return queue = 'failed_1'”等会导致“意外返回 (LocalJumpError)”错误消息。

最佳答案

为了调试的热爱,请使用更多方法,你不会像这样分解其他代码,对吗?

无论如何,这基本上就是您可能想要做的,因此您可以分解和测试您的代码:

require 'eventmachine'
require 'em-hiredis'

# This is a simple class that represents an extremely simple, linear state
# machine. It just walks the "from" parameter one by one, until it finds a
# non-empty set by that name. When a non-empty set is found, the given callback
# is called with the name of the set.
class Finder

  def initialize(redis, from, &callback)
    @redis = redis
    @from = from.dup
    @callback = callback
  end

  def do_next
    # If the from list is empty, we terminate, as we have no more steps
    unless @current = @from.shift
      EM.stop # or callback.call :error, whatever
    end

    @redis.scard(@current).callback do |scard|
      if scard.zero?
        do_next
      else
        @callback.call @current
      end
    end
  end

  alias go do_next

end

EM.run do
  @redis = EM::Hiredis.connect "redis://#{HOST}:#{PORT}"

  finder = Finder.new(redis, %w[todo failed_1 failed_2 failed_3]) do |name|
    puts "Found non-empty set: #{name}"
  end

  finder.go
end

关于Ruby EventMachine 和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10304066/

相关文章:

ruby-on-rails - Controller 中的查询缓存

ruby - ruby 中的 socket.io 和 eventmachine

ruby - 互斥 sleep 占用大量 CPU

ruby-on-rails - Rails/Devise---密码重置和重新发送确认如何重定向到主页

spring - Redis 缓存状态

ruby-on-rails - 使用 Nokogiri 将 XML 提要解析为 Ruby 对象?

java - Testcontainer 的 Redis 容器连接到与测试中定义的容器不同的容器

ruby - 是否可以使用 EventMachine 和 Ruby 1.8 发起多个并行 http 请求

ruby - 匹配字符串的键数

jquery - Rails-Jquery : Updating a Database Field on a click event