Skip to content

Instantly share code, notes, and snippets.

@calebhearth
Last active July 22, 2016 18:29
Show Gist options
  • Save calebhearth/72009d602205c78d3463f38cf80dbe32 to your computer and use it in GitHub Desktop.
Save calebhearth/72009d602205c78d3463f38cf80dbe32 to your computer and use it in GitHub Desktop.
require 'active_support/core_ext/module/delegation'
module Locking
def lock(*whitelist, &block)
Class.new(lockable) { delegate(*whitelist, to: :context) }
.new(self).instance_eval(&block)
end
private
def lockable
Class.new do
attr_accessor :context
def initialize(context)
@context = context
end
end
end
end
class Foo
include Locking
def bar
puts 'called bar'
end
end
Foo.new.lock { puts "I can call Kernel and Object methods still." }
Foo.new.lock(:bar) { bar }
Foo.new.lock { bar }
$ruby locking.rb
I can call Kernel and Object methods still.
called bar
lock.rb:18:in `block in <main>': undefined local variable or method `bar' for #<#<Class:0x007fd3b394adc0>:0x007fd3b394aa00> (NameError)
from lock.rb:13:in `instance_eval'
from lock.rb:13:in `lock'
from lock.rb:18:in `<main>'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment