Last night, I was thinking about what i think are advanced ruby language features, namely Continuations (callcc) and Binding objects. I mean advanced because I have a statically-typed oo langages background (C#, Java, C++), I discovered ruby very recently, so these language features are not very familiar to me.
I'm wondering what could be real-world use of these langages features. In my experience, everything could be done with statically typed oo langages, but I agree not very smartly sometimes. I think I figured out th开发者_如何学Pythone beauty/interest of Continuation reading that nice article from Sam Ruby : http://www.intertwingly.net/blog/2005/04/13/Continuations-for-Curmudgeons
Still, i'm lost with Binding object. Can someone provide me with some real-world examples of something that can be smartly done with Binding object but not very smartly with langages missing the ruby Binding concept?
I was thinking of rollbacking some objects to their initial state when something goes wrong during a long runing process, but I'm not sure this could be implemented with Binding object and I think could be implemented quite smartly by cloning objects before the processing and replacing modified object with their clones when something goes wrong during the processing. So this is not a valid example I think.
Thanks in advance for your help.
Binding objects are useful when you want to evaluate ERB templates.
I've used the binding class to implement a debugging hack.
class Array
def debug binding
each do |arg|
puts "arg = #{eval(arg, binding).inspect}"
end
end
end
You can use this to inspect a list of snippets of Ruby code along with what each snippet returns:
# .. some hairy code you want to debug ...
['user','current_resource', 'user.owns?(current_resource)'].debug(binding)
which will print
user = #<User id:1, username: 'joe', ...
current_resource = #<Comment id:20, ...
user.owns?(current_resource) = false
I find it very useful for quick debugging.
I needed to use a binding object to capture the scope where debug
is called so it can be used in the eval
when debug
is run. There are probably other ways to have implemented this but using the binding was easy and fast. There are also probably far better examples of what binding objects are useful for...
Take a look at http://www.seaside.st/ , it's a smalltalk web application framework. It uses continuations extensively. Best real world example on how to use it, is this CMS http://www.cmsbox.com/en/cms
精彩评论