Real-world use of binding objects in ruby

那年仲夏 提交于 2019-12-04 07:52:33

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...

Binding objects are useful when you want to evaluate ERB templates.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!