Run Once Proc

Language: Ruby

class RunOnceProc < Proc
  class MultipleCallAttempt < StandardError; end
  
  def call(*args)
    raise(MultipleCallAttempt, "You cannot call this proc more than once") if called?
    @_called = true
    super
  end
  
  def called?
    !!@_called
  end
  
end

p = RunOnceProc.new {|name| puts "hi #{name}"}

p.call("John")  # => hi John
p.call("Paul")  # => RunOnceProc:: MultipleCallAttempt: You cannot call this proc more than once
Reveal More
Added 5 months ago by Devo_normal gbuesing