Announcing the FreshBooks API for Ruby

I’ve put together a little Ruby API wrapper for the FreshBooks public API. In case you’re not familiar with it, FreshBooks is an online invoicing app designed for small to medium-sized businesses. I don’t know how many FreshBooks users use/develop in Ruby, but hopefully someone’ll find it handy.

I guess I should mention that I’ve accepted a software development position at FreshBooks, which I’ll be starting very shortly. The FreshBooks team is a good group of talented folk, and I think it’ll be a real blast working with them. I wrote this library to get a little head start on things – plus it was fun :)

If you’ve got any comments, suggestions, or bug fixes for the code, please let me know below.

PHP tools and libraries for Rails loyalists

I find myself in the thick of learning PHP, and I’ve got to admit, I’m having difficulty weaning off Ruby. If you’re in a similar position, you might find the following libraries and tools helpful – with a little less work, you can still build apps the Ruby way.

YAML loading with Spyc

YAML may just be a textual data format, but using it feels like a very Ruby thing to do, probably because most of us were introduced to it through Rails, where it’s used to describe database connections and test fixtures. Plus it doesn’t hurt that the yaml4r core library makes it dead easy to convert Ruby objects to yaml output.

It’s still good on the PHP side of things. Spyc is a YAML loader/dumper for PHP written by pre-eminent Rubyist Chris Wanstrath. (Coincidence?) Taking a cue from Rails, I’ve used it to configure database connections for a toy PHP app I’m putting together, and it works like a charm.

Update: Looks like we’ll see a Zend-friendly YAML parser soon.

Prototype and Scriptaculous

Okay, obviously Prototype and Scriptaculous are popular Javascript libraries that can be used outside of Rails, but what you might not be familiar with is Prototype’s Ruby-like syntax for Enumerable objects, complete with iterators and code blocks. If you’ve grown a fondness for Ruby methods like Enumerable#collect or #detect, then you might want to go with Prototype over other offerings. AJAX helpers are great, but these little language tweaks help make Javascript programming fun. Justin Palmer has a great tutorial on Prototype enumerables, if you’d like to read more.

Build Management with Rake

Rake is a build tool whose syntax is pure Ruby. You get all the mechanisms for describing build dependencies ala Make, combined with the flexibility of a fully featured programming language. Most people are introduced to Rake through Rails, but it can be used for anything – even building C programs. The popular Rails deployment tool Capistrano is actually a set of Rakefiles, which can also be used to deploy your PHP application.

PHP Reflection

Last, but not least, PHP 5 introduced reflection capabilities some time ago. Given the dearth of information available, I don’t think they’re used very much, but if you’ve grown accustomed to polling Ruby objects for their public interfaces, you might want to take a look. Matthew O’Phinney has a good overview of uses for reflection in PHP.

That’s what I’ve come up with so far. Any suggestions? I’ll add them to the list.

Side note: There’s always Symfony and Cake, but I figure if you’re moving from Rails to PHP, you’re probably working inside somebody else’s custom framework anyways.

Stepping off the Rails; building a contact form in pure Ruby

If there’s a common knock I keep hearing against Ruby on Rails, it’s that it’s a heavy, full-stack solution that’s overkill for small problems – like contact forms and other one-pagers. I don’t disagree with that. Still, those people might not recognize that Ruby is a perfectly capable web development platform on its own, and can serve up dynamic markup with the best of ‘em. For fun, let’s put together a good old fashion cgi script to collect and fire off an e-mail using Ruby and some core libraries.

Back to basics

The first thing you need to know about CGI scripting: your Ruby script is executed by the web server, and any text it sends to stdout is captured and sent back to the user, whether it’s HTML, binary data, or something else. Armed with that fact, here’s a simple Hello, World app that will absolutely not impress you:

#!c:\ruby\bin\ruby.exe

# Required HTTP Header
puts "Content-Type: text/html" 
puts

content = 'Hello World'

# Page content
puts '<html>'
puts '  <head><title>Sample App</title></head>'
puts '  <body>' + content + </body>'
puts '</html>'

Those puts method calls might not look so bad right now, but 50+ lines of code later, and you’ll be wishing there was a better way to generate markup. Fortunately, there is.

Embedded Ruby with ERB

Remember those RHTML files you’ve been writing in Rails? They’re actually parsed using ERB, a Ruby library for manipulating embedded Ruby templates. ERB also happens to be a core library, so including it is a snap. You can place the template in another file, but I’ll just use some heredoc statements to keep things all on one page.

Side note – .rhtml file extensions will become deprecated in favour of .erb in a future version of Rails

require 'erb'
...
content = 'Hello, World'
html_template = ERB.new <<-EOL # Heredoc
  <html>
    <head><title>Sample App</title></head>
    <body> <%= content %> </body>
  </html>
EOL
puts html_template.result

Building the form

We can’t send an e-mail without any data, so let’s rewrite the template to include input fields for our contact form. For the sake of keeping things simple, let’s just stick to a message body and a return e-mail address.

html_template = ERB.new <<-EOL # Heredoc
  <html>
    <head><title>Sample App</title></head>
    <body>
      <h1>Contact Us</h1>
      <form method="post">
        <p>E-mail<br/>
        <input type="text" name="email"/></p>
        <p>Message Body<br/>
        <input type="textarea" name="message"/></p>
        <input type="submit"/>
      </form>
    </body>
  </html>
EOL

Note that the form submits to itself. Rendered in your browser, it looks a little something like this:

Capture user params with CGI

In order to get a hold of the values posted by the user, we’ll need to use the CGI library. It’s pretty darned easy – create a new instance of the CGI class and access its parameter hash as shown below:

...
require 'cgi'
cgi = CGI.new
return_addr = cgi['email']
message = cgi['message']

if return_addr.length > 0 && message.length > 0
  # Send email here
end

# Build the contact form below
...

Send the e-mail with Net::SMTP

At this point, we should have everything we need to send the email. We can use ERB again to generate an e-mail template, and send it using Ruby’s Net::SMTP library.
...
if return_addr.length > 0 && message.length > 0
  email_template = ERB.new <<-EOL
    From: <%= return_addr %>
    To: support@yourcompany.com
    Subject: Contact Information
    Date: <%= Time.local.strftime('%m-%d-%Y') %>

    <%= message %>
  EOL
  require 'net/smtp'
  Net::SMTP.start('your.smtp.server', 25) do |smtp|
    smtp.send_message( email_template.result, 
      return_addr, 'supprt@yourcompany.com' )
  end
end

# Build the contact form below
...

If you’d like to see the script in its entirety, click here: contact-form.rb

This is a pretty simple app, and we could easily expand upon it – indicate to the user that their e-mail was sent, do some validation on the fields, and so forth. Now that you’ve got all the tools, you should be able to figure out how and where these other pieces fit.

See Also: Ruby and the Web from Programming Ruby

Update: I’ve since updated this code to use Rack instead of plain CGI.

Scribd - doc sharing for the masses

Earlier today I stumbled upon Scribd, an online document sharing community that looks set to become the YouTube of essays, books, poems and recipes. It’s got a nifty embedded document browser that’s equally adept at reading PDF, PowerPoint, and Word files, plus most (all?) docs are also available as narrated audio files. Cool beans.

See also: “Lots and lots of programming related ebooks” via DZone