Site Rewrite

Published 22 days ago  |  0 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: rails, twitter


HTTP GET and POST requests with Ruby

Published on November 7, 2007  |  3 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)
end

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: rails, get, post


Adding multiple email attachments with Ruby on Rails

Published on June 20, 2007  |  1 comment

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[:attachment1], params[:attachment2], and params[:attachment3] are the file_field_tag's from the form:

def submit_application
  CenterMailer.deliver_email_with_attachments(params[:application],params[:attachment1],params[:attachment2],params[:attachment3])
  flash[:notice] = 'Your application has been submitted.  Thank you!'
  redirect_to application_home_url and return
rescue Exception => ex
  logger.warn(ex.message)
  flash[:notice] = 'Uh oh!  There was an error sending your application.'
  redirect_to :back
end

And here is the ActionMailer method that attaches the files. I just need to call attach for each file and it creates a new attachment.

def email_with_attachments(application_fields={},attachment1=nil,attachment2=nil,attachment3=nil)
  @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] = fields[k]}

  # attach files
  unless attachment1.nil?
    attachment "application/octet-stream" do |a|
      a.body = attachment1.data
      a.filename = attachment1.name
    end
  end
  unless attachment2.nil?
    attachment "application/octet-stream" do |a|
      a.body = attachment2.data
      a.filename = attachment2.name
    end
  end
  unless attachment3.nil?
    attachment "application/octet-stream" do |a|
      a.body = attachment3.data
      a.filename = attachment3.name
    end
  end
end

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

Pretty simple!

Tagged: actionmailer, email attachment, rails


Parsing an RSS feed with Ruby

Published on June 9, 2007  |  2 comments

Parsing an RSS feed is insanely simple with Ruby. Two lines is all it takes. . .

require 'rss'
rss = RSS::Parser.parse(open('http://www.travisonrails.com/feed/posts').read, false)

Now you'll have an Array of the results, so you can do something like:

rss.items.each { |i| puts "#{i.title} - #{i.date}" }

Tagged: ruby, rss


Generate random text with Ruby

Published on June 7, 2007  |  8 comments

I'm working on a project where the user can reset their password if they've forgotten it. So, I need to generate a random password and email it to them so they can login and change it. Fortunately, I found this neat little Ruby snippet that will generate random text of a given length:

def generate_password(length=6)
  chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789'
  password = ''
  length.downto(1) { |i| password << chars[rand(chars.length - 1)] }
  password
end

Some examples:

generate_password()
>> U48ydn

generate_password(10)
>> QzWXdAkDy5

Tagged: ruby, script



©2008 Travis Roberts. All rights reserved.