Sha256: 1cb72760f907b9d8a31958441bdff22d5ac69da5dcfa897c7e6c22bd8fc1e847

Contents?: true

Size: 1.37 KB

Versions: 70

Compression:

Stored size: 1.37 KB

Contents

class CodeGenDispatch
  attr_reader :event_log

  def initialize
    @event_log = []
  end

  def self.method_added_cheat(method_name)
    if method_name.to_s =~ /^handle_(.+)$/
      handler_methods << $1
      regenerate_dispatch_method
    end
    # Cheating here, because Opal does not support method_added hook yet
    # Uncomment the super below when it does:
    # super
  end

  def self.handler_methods
    @handler_methods ||= []
  end

  def self.regenerate_dispatch_method
    dispatch_table = handler_methods.map { |event_name|
      "when :#{event_name} then handle_#{event_name}(event)"
    }.join("\n")
    class_eval %{
      def call(event)
        case event.name
        #{dispatch_table}
        end
      end
    }
  end

  def handle_foo(event)
    event_log << event
  end

  def handle_bar(event)
    event_log << event
  end

  def handle_baz(event)
    event_log << event
  end
end

klass = CodeGenDispatch
event = Struct.new(:name, :source, :args)

# Cheating here, because Opal does not support method_added hook yet
klass.method_added_cheat(:handle_foo)
klass.method_added_cheat(:handle_bar)
klass.method_added_cheat(:handle_baz)

100_000.times do
  obj = klass.new
  obj.call(e1 = event[:foo])
  obj.call(e2 = event[:bar])
  obj.call(e3 = event[:baz])
  obj.call(event[:buz])
  unless obj.event_log == [e1, e2, e3]
    raise "#{klass}: #{obj.event_log.inspect}"
  end
end

Version data entries

70 entries across 70 versions & 2 rubygems

Version Path
opal-1.8.3.rc1 benchmark/bm_dispatch_code_gen.rb
opal-1.8.2 benchmark/bm_dispatch_code_gen.rb
opal-1.8.1 benchmark/bm_dispatch_code_gen.rb
opal-1.8.0 benchmark/bm_dispatch_code_gen.rb
opal-1.8.0.beta1 benchmark/bm_dispatch_code_gen.rb
opal-1.7.4 benchmark/bm_dispatch_code_gen.rb
opal-1.8.0.alpha1 benchmark/bm_dispatch_code_gen.rb
opal-1.7.3 benchmark/bm_dispatch_code_gen.rb
opal-1.7.2 benchmark/bm_dispatch_code_gen.rb
opal-1.7.1 benchmark/bm_dispatch_code_gen.rb
opal-1.7.0 benchmark/bm_dispatch_code_gen.rb
opal-1.7.0.rc1 benchmark/bm_dispatch_code_gen.rb
opal-1.6.1 benchmark/bm_dispatch_code_gen.rb
opal-1.6.0 benchmark/bm_dispatch_code_gen.rb
opal-1.6.0.rc1 benchmark/bm_dispatch_code_gen.rb
opal-1.6.0.alpha1 benchmark/bm_dispatch_code_gen.rb
opal-1.5.1 benchmark/bm_dispatch_code_gen.rb
opal-1.5.0 benchmark/bm_dispatch_code_gen.rb
opal-1.5.0.rc1 benchmark/bm_dispatch_code_gen.rb
opal-1.4.1 benchmark/bm_dispatch_code_gen.rb