Articles tagged with core_ext

Getting a glimpse into Net::HTTP requests

core_ext February 16 2008

While trying to debug some HTTP code, I wanted to be able to see what the actual HTTP request looked before it was sent. So, I added a #to_s method:

require 'stringio'

class Net::HTTPGenericRequest
  def to_s
    io = StringIO.new
    exec(io, '1.1', path)
    io.string
  end
end

All the built in requests extend HTTPGenericRequest, so now I can call #to_s on any request:

request = request = Net::HTTP::Get.new('/some/path')
request.set_content_type 'text/html'
request.basic_auth 'username', 'password'

puts request.to_s

Which gives me:

GET /some/path HTTP/1.1
Accept: */*
Content-Type: text/html
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=

I had also intended to add a #to_s method to the response, but it wasn’t obvious how to accomplish that, and I found my bug before I needed it. So, if anyone feels ambitious…

posted by brandon | updated February 17th 12:08 PM | 1 comment

Round floats to the nearest X

core_ext July 18 2007

For those pesky times when whole numbers just won’t cut it, but you only want some precision.

7.7.round(0.5)   #=> 7.5
7.95.round(0.5)  #=> 8
8.2.round(1.5)   #=> 7.5
8.3.round(1.5)   #=> 9

The magic, courtesy of Daniel Morrison:

class Float
  def round(round_to = 1.0)
    mod = self % round_to
    rounded = self - mod + (mod >= round_to/2.0 ? round_to : 0)
    rounded % 1 == 0 ? rounded.to_i : rounded
  end
end

Note that do to some quirks with Ruby’s handling of floats, you won’t get what you expect in some situations:

3.5.round(0.2)   #=> 3.4, instead of 3.6
posted by brandon | 2 comments

About

I'm Brandon Keepers, a web application developer that likes beautiful code, valid markup and adherence to standards. As a part of Collective Idea in Holland, Michigan, I practice Agile software development primarily using Ruby on Rails.

-86.103171 42.785037

Contact:

more »

Syndicate