Code Golf: Numeric Diamonds
DEC
08
2007
Here is my submission for the Numeric Diamonds challenge. Code size: 219 bytes.
[9,36,100].each{|n|s=Math.sqrt(n).to_i
w=n.to_s.size.to_i
a=[]
j=s+s-1
j.times{a<<[" "*w]*j}
x=0
y=s-1
f=x
g=y
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}}
HTTP GET and POST requests with Ruby
NOV
07
2007
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?
Adding multiple email attachments with Ruby on Rails
JUN
20
2007
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 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 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?
end
end
The "application/octet-stream" is the generic MIME type for attaching unknown file types.
Pretty simple!
Tagged: tutorial, rails, email attachment, actionmailer
Parsing an RSS feed with Ruby
JUN
09
2007
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}" }
Generate random text with Ruby
JUN
07
2007
UPDATE: Changed the generate_password method slightly based on commenter Dave Burt's suggestion.
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.times { |i| password << chars[rand(chars.length)] }
password
end
Some examples:
generate_password >> U48ydn generate_password(10) >> QzWXdAkDy5
Popular Posts
Search
Tags
actionmailer activerecord ajax apache apple barcamp caching capistrano centos code golf css db delete eager loading ebay email attachment erb flash ftp fun generators get haml helpers ie sucks javascript jquery lightbox lost merb net ftp paperclip passenger php plexus post presentation rails rails machine railsconf redesign rest rjs routes rss ruby ruby on rails safari script sinatra symfony text replacement tips tutorial twitter xhtml
Projects
© 2010 Travis Roberts. All rights reserved.