Last active
July 22, 2016 18:29
-
-
Save calebhearth/72009d602205c78d3463f38cf80dbe32 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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