元编程 Ruby 个便捷方法

Metaprogramming Ruby convenience methods

在我的程序中,我使用了状态机,并且有很多方便的方法。我目前正在创建一长串“?”模型中的方法。

def purchase_ready?
    self.current_state == 'purchase_ready'
end

def completed?
    self.current_state == 'completed'
end

def region_prepared?
   self.current_state == 'region_prepared'
end

执行此操作的元编程方法是什么?

...这是一个答案!

感谢这个博客:http://rohitrox.github.io/2013/07/02/ruby-dynamic-methods/

[:purchase_ready, :completed, :region_prepared].each do |method|
   define_method "#{method}?" do
      self.current_state == "#{method}"
   end
end

偷懒的方法是使用BasicObject#method_missing:

class State
  def initialize state
    @state = state
  end

  def method_missing name, *args
    case name
    when :purchase_ready, :completed, :region_prepared
      @state == name
    else
      super
    end
  end
end

state = State.new(:purchase_ready)
state.purchase_ready
  #=> true 
state.completed
  #=> false
state.region_prepared
  #=> false
state.purchase_not_ready
  #-> NoMethodError: undefined method `purchase_not_ready' for
  #   #<State:0x007f9dfb9674b8 @state=:purchase_ready>