.
Bitland.Net Security Notes            Comments? email jwilkins-at-bitland*net
More information on the author at Jonathan Wilkins's home page
RSS feed available at http://www.bitland.net/index.rss               Add to Google
Archives: 2007, 2006, 2005, 2004, 2003, 2002, 2001, 2000


Ruby's equivalent of Python's setattr  |  (2007/09/17 17:52)

I am still really new to Ruby but I'm jumping in with both feet. As a result I figured out metaprogramming before I knew what the ! operator did. Anyway, I was trying to find out the equivalent of Python's setattr when I came across Hal Fulton's 'An Exercise in Metaprogramming with Ruby'. That and some hints from a ruby-talk thread on attr_accessor allowed me to translate this Python code I'd written for dealing with MySpace profiles from:
print "Getting Profile Nodes.."
for p in ['ProfileMusic', 'ProfileGeneral', 'ProfileBooks', 'ProfileHeroes']:
  try:
    v = self.soup.first('td',id=p).string
    setattr(self, p, v)
  except:
    setattr(self, p, None)
Into this Ruby:
(page/"td").each do |t|
  tid = t.attributes['id']
  if /Profile([.]*)/ =~ tid
    pname = tid[7..-1].downcase
    pname = pname.gsub(/[ \/]/, "_").gsub(/[^\w]/, "").squeeze('_')
    instance_variable_set("@"+pname, t.inner_html)
    eval("class << self; attr_accessor :#{pname}; end")
  end
end
The Ruby uses Hpricot instead of BeautifulSoup, but is more generalized and OOish. I'm a little uncomfortable with the security of the eval, but the technique is useful and I couldn't google a better solution. If you have something better, let me know.

+digg  |  +del.icio.us   |    [Ruby ]   |   Permanent link

RSS feed available at http://www.bitland.net/index.rss