Code Samples

All of the code samples have now been consolidated and moved to my blog at http://house9.blogspot.com/. Many google searches still point here so I am leaving this blog operational.

Tuesday, March 23, 2010

sorting rails view with will_paginate plugin

This solution for sorting data on rails index actions does NOT use ajax. Sometimes sorting with ajax is nice but often it is not actually as user friendly; breaking the browser back button, etc...

Disclaimer 1: this code is probably using all kinds of ruby anti-patterns :) - but it is a very simple implementation and so I just went with it...

Disclaimer 2: the title of the post might be a little miss leading as you can use this with or without the will_paginate plugin. In my case I am using it with the will_paginate plugin - and I highly recommend it!

put this file in your rails lib directory /lib/sort_index.rb

in your controller code, set up the SortIndex::Config (you can have more than one if you have multiple actions that need to support sorting

then in your view code render your table headers using the sort object

Does not support the following:
  • additional attributes on the anchor tags
  • additional attributes on the table header tags
  • additional query string parameters - might add this later, would be nice for search results

Wednesday, January 6, 2010

Ruby Http Get with Net::HTTP


Resources



require 'net/http'
require 'uri'

def get_html_content(requested_url)
url = URI.parse(requested_url)
full_path = (url.query.blank?) ? url.path : "#{url.path}?#{url.query}"
the_request = Net::HTTP::Get.new(full_path)

the_response = Net::HTTP.start(url.host, url.port) { |http|
http.request(the_request)
}

raise "Response was not 200, response was #{the_response.code}" if the_response.code != "200"
return the_response.body
end

# this will fail with ArgumentError: HTTP request path is empty
s = get_html_content("http://www.google.com")
# these should be fine
s = get_html_content("http://www.google.com/")
s = get_html_content("http://github.com/search?q=http")
# above code does not handle redirects but raises exception for non-200
s = get_html_content("http://www.yahoo.com/") # http 302

Ruby Regex to remove script tags


Resources
Custom Search
< ... back