Discovering Python

Despite my strong bias towards Ruby, I am finally learning Python.
I think functional nature of the Python is what makes it attractive to me. After spending a lot of time with Erlang and Ruby, I found Python to be an interesting hybrid.. kind of “in between” Ruby magic and pure functional feel of Erlang. I like the fact that pretty much all Ruby meta programming is still possible and on top of that Python has a very good support for functions, higher level functions, which makes is very interesting combination for me. For a few years now I’ve been hearing people talking about it, but it did not register with me until I started playing with it. One thing for sure I am going to put more time into it…

Functional Example (very Erlangish and Rubyish in the same time 🙂 )

In [21]: def wrapper(fun):
      ....:   def func(*args, **kwargs):
      ....:     print " begin execution %s " % (fun.__name__)
      ....:     fun(*args, **kwargs)
      ....:     print " finished execution %s " % (fun.__name__)
      ....:   return func
      ....: 

In [22]: def hello(msg):
      ....:   print "hello %s" % (msg)
      ....: 

In [23]: f = wrapper(hello)

In [24]: f("Alex")
 begin execution hello 
 hello Alex
 finished execution hello 

Advertisements

Fun with Sinatra

A few days ago I started playing with Sinatra, very small, but very nice Ruby web framework. It takes about 15 minutes to read the book and get started. Since I’ve been using Rails for some time now, I started to wonder: what would it take to implement something similar to Rails respond_to functionality… This is what I’ve got so far:

helpers do

def respond_to(&block)
class << (mappings = {} )
def method_missing(name, &resp)
self[name.to_s] = Proc.new(&resp)
end
end
yield mappings
handler = mappings[params[‘format’]] if params[‘format’]
handler.call if handler
end

end

This will add a helper method, which can be used in all routes. Now, we need to add a before filter to make sure format is added to the request_path:

before do
ext = request.path_info =~ /.*([.]([^.]*))$/ ? $1 : ‘.html’
request.path_info = request.path_info + ext unless $1
content_type ext
end

All there is left to do is to define a route, which will allow for format parameter, and use our helper method:

get ‘/hello.:format’ do
respond_to do |format|
format.html { “You have requested HTML format” }
format.json { { :message => ‘hello’ }.to_json }
format.xml  { “<hello />”}
end
end

Now it looks more like Rails 😉