Last active
September 25, 2015 09:06
-
-
Save luislee818/a79803112033fb91e03d to your computer and use it in GitHub Desktop.
Encapsulate with closure in object, using JavaScript and Ruby
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
var myClosure = function() { | |
var secret = 42, getSecret, inc; | |
getSecret = function() { return secret; }; | |
inc = function() { secret += 1; }; | |
return { | |
getSecret: getSecret, | |
inc: inc | |
}; | |
} | |
var o = myClosure(); | |
console.log(o.getSecret()); // 42 | |
o.inc(); | |
console.log(o.getSecret()); // 43 |
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
def my_closure | |
secret = 42 | |
Object.new.tap do |o| | |
o.send(:define_singleton_method, :get_secret) { secret } | |
o.send(:define_singleton_method, :inc) { secret += 1 } | |
end | |
end | |
o = my_closure | |
puts o.get_secret # 42 | |
o.inc | |
puts o.get_secret # 43 |
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
# adapted from Metaprogramming Ruby 2 book, p83 | |
class Foo | |
def define_methods | |
shared = 0 | |
Kernel.send(:define_method, :counter) { shared } | |
Kernel.send(:define_method, :inc) { |x| shared += x } | |
end | |
end | |
o = Foo.new | |
o.define_methods | |
puts o.counter | |
o.inc(4) | |
puts o.counter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment