Back

Ruby get a list of responses for an objects instance methods

added on :: 12 November 2014


a = {}
(cls_obj.methods - Object.methods).each do |m|
begin
a[m.to_s] = cls_obj.send(m.to_s).to_s
rescue => e
a [m.to_s] = e
end
end
a


Say for example I like to get a list of images on a website.

require 'mechanize'
URL = "http://iamfree.com"
page = Mechanize.new.get(URL)
page.image_urls
 Then if you like to know list of methods available for page.image_urls.first object
 page.image_urls.first.methods - Object.methods
 Then you like to know the responses for method calls.
       
a = {}
(page.image_urls.first.methods - Object.methods).each do |m|
begin
a[m.to_s] = page.image_urls.first.send(m.to_s).to_s
rescue=> e
a [m.to_s] = e
end
end
a

result would be

{"request_uri"=>"/site-images/i-am-free.jpg", "default_port"=>"80", "scheme"=>"http", "host"=>"iamfree.com", "port"=>"80", "registry"=>"", "path"=>"/site-images/i-am-free.jpg", "query"=>"", "opaque"=>"", "fragment"=>"", "parser"=>"#", "component"=>"[:scheme, :userinfo, :host, :port, :path, :query, :fragment]", "set_scheme"=>#, "scheme="=>#, "userinfo="=>#, "user="=>#, "password="=>#, "set_userinfo"=>#, "set_user"=>#, "set_password"=>#, "userinfo"=>"", "user"=>"", "password"=>"", "set_host"=>#, "host="=>#, "hostname"=>"iamfree.com", "hostname="=>#, "set_port"=>#, "port="=>#, "set_registry"=>#, "registry="=>#, "set_path"=>#, "path="=>#, "set_query"=>#, "query="=>#, "set_opaque"=>#, "opaque="=>#, "set_fragment"=>#, "fragment="=>#, "hierarchical?"=>"true", "absolute?"=>"true", "absolute"=>"true", "relative?"=>"false", "merge!"=>#, "merge"=>#, "+"=>#, "route_from"=>#, "-"=>#, "route_to"=>#, "normalize"=>"http://iamfree.com/site-images/i-am-free.jpg", "normalize!"=>"", "component_ary"=>"[\"http\", nil, \"iamfree.com\", 80, \"/site-images/i-am-free.jpg\", nil, nil]", "select"=>"[]", "coerce"=>#, "find_proxy"=>""}


The above would give you the method name and the response. The reason for the "rescue" is some methods are expecting parameters. So those ones going to raise a "ArgumentError" and blow up the block.  If you dont want to see the argument errors; then do a dont aregue . That would silently ignore the error and go to the new one.

   rescue
 end

 or to report the error in a log

begin
    # do stuff
rescue Exception => e
    thelog.error("#{e} exception occurred: #{e.message}")
    thelog.error("Stack trace: #{e.backtrace.map {|l| "  #{l}\n"}.join}") 
 
end


or

print e.backtrace.join("\n")
Back