Monday, 5 March 2012

Rails views: .html.haml vs .haml / html.erb vs erb

Normally I use the .haml extension for my views. Today while working on one Rails app I have learned why in some cases one cannot just use .haml.


class Contacts::ApplicationController
respond_to :json, :html
def index
respond_with Contacts.all
end
end
view raw gistfile1.rb hosted with ❤ by GitHub
Given the above controller, if you just use .haml instead of .html.haml every response will be rendered using that .haml template.

Initially I had created app/views/contacts/index.haml for responding to html requests.
After I changed 'repond_to :html' to 'respond_to :html, :json' -- I was confused when I saw an HTML response when fetching '/contacts.json'.

Renaming 'app/views/contacts/index.haml' to index.html.haml' solved the problem, Rails no longer used index.haml to render the JSON response.


Friday, 4 March 2011

Static methods or class methods in Ruby and Python

Today when learning how to define a class method in Ruby I was curious how would I do that in Python. Here I have demonstrated how static/class methods look in these languages.


Ruby


class Greeter
def self.say_hi name
puts "Hi #{name}."
end
end
=begin
Output:
irb(main):007:0> Greeter.say_hi 'Ruby'
Hi Ruby.
=end
view raw gistfile1.rb hosted with ❤ by GitHub


Python


class Greeter:
@staticmethod
def say_hi(name):
print ('Hi %s.') % name
#Output:
# Greeter.say_hi('Python')
# >> Hi Python.
view raw gistfile1.py hosted with ❤ by GitHub