元编程Ruby便捷方法

时间:2015-03-30 17:47:30

标签: ruby metaprogramming

在我的程序中,我使用状态机,并有许多方便的方法。我目前正在创建一个很长的清单"?"模型中的方法。

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

元编程的方法是什么?

2 个答案:

答案 0 :(得分:5)

......这是一个答案!

感谢此博客: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

答案 1 :(得分:1)

懒惰的方式是使用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>