0

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

这里是瘦子。

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等时,它工作得很好。我错过了什么神圣的东西?

4

1 回答 1

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将来会显示错误...

于 2013-10-31T18:43:39.933 回答