Site Rewrite

Jun 08, 2008  -  Comments

I've been really lazy about updating the blog lately. I'd like to say that I've been busy working on some cool new project, but the reality is that I bought a PS3 a few months ago, and all of my free time has been taken up by Call of Duty 4 and Grand Theft Auto. By the way, if you're on PSN, send me a friend request (deadwards).

To try and force myself to get back into the blog, I decided to re-write it since Rails 2.1 was recently released. It was really funny looking at some of my old code (keep in mind, I originally wrote this blog as my first foray into Rails, circa May 06). All of the code has at least been refactored, and in many cases totally re-written. I've also added caching where I can to increase the speed a bit. Hopefully, this will be the kick in the ass I need to get back to blogging.

ps I finally broke down and created a Twitter account.

Tagged: railstwitter

Code Golf: Choose

Jan 16, 2008  -  Comments

Here is my submission for the Choose challenge. Code size: 88 bytes.

def g(r)(1..r).inject(1){|m,n|m*n}end
p g(x)/(g(y)*g(x-y))

Tagged: rubycode golf

Code Golf: Numeric Diamonds

Dec 08, 2007  -  Comments

Here is my submission for the Numeric Diamonds challenge. Code size: 219 bytes.

j.times{a<<[" "*w]*j}
1.upto(n){|t|a[x][y]=t.to_s.rjust w
t%s<1 ?(x=f+1;f=x;y=g-1;g=y):(x+=1;y+=1)}
a.each{|r|puts r.join.rstrip}}

Tagged: rubycode golf

HTTP GET and POST requests with Ruby

Nov 07, 2007  -  Comments

A while ago, I was working on a project for a client that used a third-party newsletter generator for capturing and storing email addresses. To add an email address, the application spits out some code for a form that you can put on your site. A user supplies his name and email address, then submits the form and it gets stored within the third-party app's database.

The problem arose when they wanted to automatically subscribe not only people who requested subscriptions, but also everyone who used the online contact form AND anyone who used the 'email to a friend' feature on one of the interior pages. Obvious misgivings aside, I set out to do what I was told (like any good drone).

The problem was, I needed to do a POST request to subscribe the person to the third-party app, but I couldn't do that with a regular form because I was already posting to the actual action being invoked. Luckily, Ruby has a built in Net::HTTP class for generating GET and POST requests from within the code.

Here is the method I needed to add the POST request to:

def email_to_friend
  ...other code...
  # now, do the dirty work
  require 'net/http'
  # get the url that we need to post to
  url = URI.parse('http://www.url.com/subscribe')
  # build the params string
  post_args1 = { 'email' => params[:email] }
  # send the request
  resp, data = Net::HTTP.post_form(url, post_args1)

The post_form method returns a Net::HTTPResponse object and an entity body string (in Ruby 1.8, it only returns the Net::HTTPResponse object). You can also use the post method.

Similarly, you can perform a GET request on a URL like so:

require 'net/http'
result = Net::HTTP.get(URI.parse('http://www.site.com/about.html'))
# or
result = Net::HTTP.get(URI.parse('http://www.site.com'), '/about.html')

The get method returns a String.

That's simple enough, right?

Tagged: railsgetposttutorial

Adding multiple email attachments with Ruby on Rails

Jun 20, 2007  -  Comments

I was building some forms for a client that required the user be able to upload supporting documents along with the application. I had implemented emailable forms before with single attachments, but never multiple. Turns out, it was just as simple to do, I just needed to call the attach function for each file I wanted to attach.

Here is the method in my controller that calls the ActionMailer class to send the email, where params[:file1], params[:file2], and params[:file3] are the file_field_tag's from the form:

UPDATE: I've re-factored this after Shawn suggested that it could be simplified into an array and iterated over.

def submit_application
  @uploaded_files = []
  @uploaded_files << params[:file1]
  @uploaded_files << params[:file2]
  @uploaded_files << params[:file3]
  ContactMailer.deliver_email_with_attachments(params[:application], @uploaded_files)
  flash[:notice] = 'Your application has been submitted.  Thank you!'
  redirect_to application_home_url
rescue Exception => ex
  flash[:notice] = 'Uh oh!  There was an error sending your application.'
  redirect_to :back

And here is the ActionMailer method that attaches the files. I just need to iterate over the files, calling attach for each one.

def email_with_attachments(application_fields={},files=[])
  @headers = {}
  @sent_on = Time.now
  @recipients = 'client@domain.com'
  @from = 'info@domain.com'

  @subject = 'Here are some file attachments'
  application_fields.keys.each {|k| @body[k] = application_fields[k]}

  # attach files
  files.each do |file|
    attachment "application/octet-stream" do |a|
      a.body = file.read
      a.filename = file.original_filename
    end unless file.blank?

The "application/octet-stream" is the generic MIME type for attaching unknown file types.

Pretty simple!

Tagged: tutorialrailsemail attachmentactionmailer