Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Python OpenStruct

// Just a OpenStruct port to Python

   1  
   2  class OpenStruct:
   3  	def __init__(self, **dic):
   4  		self.__dict__.update(dic)
   5  	def __getattr__(self, i):
   6  		if i in self.__dict__:
   7  			return self.__dict__[i]
   8  		else:
   9  			raise AttributeError, i
  10  	def __setattr__(self,i,v):
  11  		if i in self.__dict__:
  12  			self.__dict__[i] = v
  13  		else:
  14  			self.__dict__.update({i:v})
  15  		return v # i like cascates :)
  16  		
  17  o = OpenStruct(b=2)
  18  o.a=1
  19  print o.a,o.b

Quick Flickr search in Ruby

// Examples for the three listed APIs weren't working. Instead of choosing one and debugging it, I chose to do something quick and dirty. "MY_API_KEY" and other params would need to be removed to make this more generic. A naive mapping of API method calls that take hashes, and returns an OpenStruct is an approach I'm considering, as it would likely break less often and require less code.

   1  
   2  require 'net/http'
   3  require 'rexml/document'
   4  require 'ostruct'
   5  
   6  class Flickr < OpenStruct
   7    include REXML
   8  
   9    def Flickr.search(text)
  10      doc = Document.new(
  11              Net::HTTP.get(
  12                URI.parse('http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=MY_API_KEY' +
  13                          '&extras=license,owner_name,original_format&license=4,5&per_page=20&sort=interestingness-desc' +
  14                          '&text=' + text)))
  15       throw "flickr error" unless doc.root.attributes['stat'] == "ok"
  16       doc.root.elements['photos'].get_elements('//photo').collect {|photo| photo << Flickr.new(photo) }
  17    end
  18  
  19    def initialize(e)
  20      super(e.attributes)
  21      self.new_ostruct_member("photo_id")
  22      self.photo_id = e.attributes['id']
  23    end
  24  
  25    def to_url(image_type="s")
  26      "http://farm#{farm}.static.flickr.com/#{server}/#{photo_id}_#{secret}_#{image_type}.jpg"
  27    end
  28  end
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS