Rails哈希迭代与Ruby?

时间:2013-10-31 18:02:37

标签: ruby hashmap ruby-on-rails-4

我一直有一些奇怪的行为。这是你看到的那些问题之一,并认为它甚至不应该是一个问题!

这是瘦的。

class Partner < ActiveRecord::Base
  STATUS = {
    pending: 0,    # 0 account has a pending billing request (but is not yet open)
    active: 1,     # 1 account has an active base subscription
    suspended: 2,  # 2 account has been suspended (e.g. after a base subscription decline)
    expired: 3,    # 3 base subscription has expired
    incomplete: 4, # 4 partner application process incomplete
    closed: 5,     # 5 account has been permanently closed
    cancelled: 6   # 6 account has been cancelled by user (but is still unexpired)
  }
  after_initialize :setup_status_enums

  def setup_status_enums
    puts STATUS.inspect
    STATUS.each do |key, val|
      puts "Doing enum #{key}"
      define_method "#{key.to_s}?" do
        send("status") == key
      end

      define_method "#{key.to_s}!" do
         send("status=", val)
      end
    end
  end
end

{:pending=>0, :active=>1, :suspended=>2, :expired=>3, :incomplete=>4, :closed=>5, :cancelled=>6}
Doing enum pending

{:pending=>0, :active=>1, :suspended=>2, :expired=>3, :incomplete=>4, :closed=>5, :cancelled=>6}
Doing enum pending

{:pending=>0, :active=>1, :suspended=>2, :expired=>3, :incomplete=>4, :closed=>5, :cancelled=>6}
Doing enum pending

{:pending=>0, :active=>1, :suspended=>2, :expired=>3, :incomplete=>4, :closed=>5, :cancelled=>6}
Doing enum pending

(一遍又一遍)

如您所见,它只是看到“待定”

当我将检查过的哈希{:pending=>0, :active=>1, :suspended=>2, :expired=>3, :incomplete=>4, :closed=>5, :cancelled=>6}投入IRB并运行each等时,它就可以了。我错过了什么是神圣的?

1 个答案:

答案 0 :(得分:0)

好的。就像我怀疑的那样。我感觉不是很糟糕,但它仍然很愚蠢。

我的rake测试没有将失败的代码带到控制台,我不知道为什么,但是当我在rails c中运行它时,我得到了未定义的方法异常。这更具描述性。我不确定为什么rake test没有向我显示这些错误。

无论如何,修复程序如下。

        def setup_status_enums
        class << self
            STATUS.map do |key, val|
                raise "Collision in enum values method #{key}" if respond_to?("#{key.to_s}?") or respond_to?("#{key.to_s}!") or respond_to?("#{key.to_s}")

                define_method "#{key.to_s}?" do
                    send("status") == key
                end

                define_method "#{key.to_s}!" do
                    send("status=", val)
                end

                scope key.to_sym, lambda { where(status => val) }
            end
        end
    end

define_method必须位于class << self范围内。

谢谢大家帮助我深入研究这个问题。也许rake将来会出现错误......