0

How can I assign scopes dynamically from within a class << self context?

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 status
    STATUS.key(read_attribute(:status))
  end

  def status=(s)
    write_attribute(:status, STATUS[s])
  end

  private

    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

end
Volte
  • 1,905
  • 18
  • 25

2 Answers2

0

Something like this should work. You can just iterate through your STATUS hash right in your class definition.

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)
  }

  STATUS.each do |key, val|
    define_method "#{key.to_s}?" do
      status == key
    end

    define_method "#{key.to_s}!" do
      status = val
    end

    scope key, lambda { where(status: val) }
  end

  ...
end
struthersneil
  • 2,700
  • 10
  • 11
0

It seems that you are looking for a state machine.

In Ruby, check out the state_machine or aasm gems. You can then define scopes based on the state column (or you could name is status.)

A state machine will also help you manage transitions between statuses, so you can run callbacks or validations only on specific transitions or statuses.

Chris
  • 11,819
  • 19
  • 91
  • 145