Use TinyURL from Ruby

I recently found myself needing to use TinyURL on a client project.  I did a bit of scouring the web for some Ruby code to solve the problem but with little success.  Much to my surprise they don’t have an available API, but they do have a way to access over HTTP.

This is a simple Ruby class to use TinyURL.  Note: this depends on HTTParty, so add to your project.

class Tinyurl 
include HTTParty
base_uri 'tinyurl.com'

def shorten(url)
self.class.get("/api-create.php?url=#{url}")
end
end

You can find the Gist on Github. Hopefully you find this code useful. Enjoy!

I Backed The Ruby 2.0 Walkthrough on Kickstarter and So Should You

Ruby20

It was announced at RubyConf that Ruby 2.0 would be released in February 2013 and a preview available immediately.  If you use rvm, you can try it out pretty easily.

The problem is, there are many changes coming.  How are you going to know what’s different from Ruby 1.9.x?  What about all the way back to 1.8.x?  I think it will take any one of us a significant amount of time to sort it all out, but it doesn’t have to.

There really is a rather simple answer; it’s a Kickstarter project by our Ruby friend Peter Cooper called The Ruby 2.0 Walkthrough.  Peter is looking for a small sum of money to help pay for his time to create this valuable asset.

What do you get?

Ruby 2.0 launches in February 2013 and at that time I’ll be selling the screencasts alone for $19 and the screencasts + e-book for $29. By backing the project now, you’ll get the same material for less and depending on what tier you go for you could get access to special bonuses and benefits that I WON’T be offering when it goes on general sale (like update e-mails, consultancy time or a limited PRINT edition). Also, having people pledge to the project will ensure I stick to it and get it done which is the main motivation for this campaign.

I am backing this project and so should you.  Why?  

  • The resource created will be valuable to everyone moving to Ruby 2.0.
  • The small amount of money to back the project will pay for itself in the time you save.  Minutes based on your hourly rate, I’m sure.
  • Peter would like your support.  He provides so much value to our community with his weekly newsletters for Ruby, JavaScript, HTML5 and others, that when someone so giving asks for support..it’s a no-brainer.
  • Peter needs the pressure from us, by raising the money to get it done.
Head over to Kickstarter and support The Ruby 2.0 Walkthrough.  Many less worthy projects have been funded.

 

Get Your RubyTapas On

Rubytapas

I really love the efforts being put forward by people in our developer community, lots of cool new tools and especially screen casts.  Screen casts are a great way to spend some time and learn something new.

One new screen cast that has quickly become one of my favorites is RubyTapas by Avdi Grimm.  Avdi is a speaker, writer and a Ruby Rouge.

What’s RubyTapas?

These are short, 2.5 to 7 minutes in length, but are laser focused on a very specific aspect of Ruby and published 3 times a week. 

RubyTapas is for the busy Ruby or Rails developer who is ready to reach the next level of code mastery. Short screencasts three times a week will introduce you to a wide variety of intermediate to advanced Ruby concepts and techniques, as well as core Object-Oriented design principles. Lead by head chef Avdi Grimm (author of Exceptional Ruby and Objects on Rails), you’ll go from journeyman to master, one small, tasty plate at a time.

As I write this Avdi has published his 13th episode which covers singleton objects.  The growing list of episodes can be found on the RubyTapas site.   Subscribing to the full list requires a subscription, only $9 per month..so a great deal.

What’s to love about these?

Each episode is a super focused topic, great video and great sound.  This isn’t the best part in my humble opinion; each episode comes with a very well commented Ruby file as well as an HTML document containing the episode explained so you can get a deeper understanding of the concept.  

I have gone through all the episodes and they are pure Ruby, no Rails no Sinatra..just pure Ruby.  I have been working with Ruby for a good number of years and I am learning a bunch from these, great style and techniques.  I wouldn’t say they are for beginners but your mileage may vary.

I’m not affiliated with Avdi at all, just a happy subscriber.  It’s sometimes hard to filter the good from the bad out there.  

Happy Hacking!!

Goruco 2011

IMG 0070

I had never had the opportunity to attend Goruco in New York City before, not because I couldn’t make it but rather because I wasn’t fast enough to get a ticket before the conference sold out.  Now I can understand why it sells out so fast, it is a fantastic conference run by a great group and organized with precision.

I decided to make the trip from CT to NYC the same day as the conference and return the evening after it ended, making for a long day indeed.  Getting up at 3:30 AM seems almost unnatural to drive an hour to meet a friend to make the trip by train from New Haven and arriving at Grand Central Station just after 7:30 AM with my friend and fellow Rubyist, Mike Morris of RecDesk (great software for your recreation department, by the way).

A short trip by subway to lower Manhattan put us at Pace University with plenty of time to settle into the conference.

The Venue

Pace University is the host for Goruco and has been in the past.  Since it is a university and setup to handle students, it makes a perfect back drop to spending the day talking about Ruby.  The setting in downtown Manhattan is a great place in a wonderful city.

IMG 0083

Just a short walk from Pace visitors are treated with the new World Trade Center under construction.

The Lineup of Talks

Whenever I attend a conference there are always talks that stand out for me, either because the content is great or the topic is something I am working on or interested in at the moment or maybe both.

IMG 0079

As you can see here, Evan Phoenix waves to the crowd while demonstrating some sleight of hand.

There were 7 talks plus RejectConf and of the seven, Jeremy Ashkenas’s talk titled Coffeescript for the Well-Rounded Rubyist and Evan Phoenix’s talk, Build it and they will come (Rubinius Edition) were the two talks that stood out.  Jeremy is the creator of CoffeeScript and Evan the creator of Rubinius and this fact alone makes their deep knowledge shine through. When a speaker knows a subject as deep as these two, it’s obvious in the delivery and the their ability to answer any question in great detail.

The announcement at RailsConf that CoffeeScript would be included by default in Rails 3.1 and the fact that I have never enjoyed writing JavaScript meant I really was looking forward to this talk.  I had been playing around with CoffeeScript recently after listening to the screencasts from RailsCasts and PeepCode and really liked what I saw.  An opportunity to hear the creator of CoffeeScript, Jeremy Ashkenas, speak could not be passed up.  

Engine Yard has been 100% committed to Ruby and the development of Rubinius for a long time and this level of commitment has piked my interest over the past several months.  I have spend time with Rubinius, testing my applications and using it for new development.  It has been very stable and performant and I look forward to the day it supports 1.9.x.  I think once we see version 2.0 will be the time to start moving Rubinius to production.  So this talk was important to me and Evan did not disappoint.  He laid out a clear roadmap for the product with a call to action for developers to use it, report bugs and help fix them.

The other 5 talks were also really good, along with the end of day lightening talks made for a day of learning.

New Friends

I met up with a lot of folks who I only knew from Twitter, blogs or some other way.  I always find it interesting to walk around and try to catch a glimpse of people’s name badges to see if they are familiar.  It’s also interesting to try to match a Twitter avatar to a real face.

I am glad for the opportunity to meet these people finally face-to-face.

Missed Opportunities

The conference organizers planned for a cruise on the Manhattan water which included dinner and drinks but our lack of planning left us to only watch as others sailed off.  After a dinner and a couple cold beers we headed back to CT.  The trip home seemed like a longer journey than our arrival, finally getting in at 2:00 AM.

I would have liked to spend the entire weekend in the city and attend all the activities the organizers planned but timing didn’t work out.  I am sure everyone had a great time.

Next Year

It was a great event covering a great day.  I plan to be back next year but I will be spending the weekend in the city and hopefully there will be another cruise at Goruco 2012.

If I had one suggestion to make to those planning Goruco next time, I wouldn’t mind seeing this as a two-day event full of talks.

Makandra Notes for Rails Developers

The Ruby Rails consulting shop Makandra recently opened their internal knowledge base of how-tos and code snippets for all to see and use.  The announcement about the project indicates 500+ links:

This September we decided to take our in-house knowledge base and publish it for everyone to see. makandra notes contains some 200 HOWTOs and 500+ links for Ruby, Rails, RSpec, Cucumber and Javascript and is growing every day.

Whether you’re looking to deliver Paperclip attachments securely, test concurrent Ruby code or marry Capybara with SSL-enabled applications, chances are we already solved your problem for you.

The reality is as of this writing, 718 notes are listed.  It’s a good resource and one I hope they add to and either let others contribute to or open source the application for others to use to build internal/external knowledge bases.

The search is fast too and real-time, narrowing down results as I typed.

makandra

Besides having some useful information you can also see the user interface is nice and clean.  The resource is from a Rails shop but it is not just for Rails issues but rather the issues Rails developers deal with each day, from Ruby, Rails and JavaScript to Ubuntu server administration and cron jobs.

Way to go Makandra and thanks for the resource.

Delete Large Numbers of Amazon S3 Files using Ruby

I recently found I problem I needed to solve; remove hundreds of thousands of files from Amazon S3.  I mean, it had to be a common problem, right?  Well, it certainly be a common problem but the solution was less than common.

I tried a few tools available, both the tool from the Amazon S3 site but it keep erroring out and I was never sure why.  I then went to third-party tools used for managing S3 buckets but their either errored-out or behaved as if they worked but later determined did nothing.

I posted my need on Twitter and was pointed to a solution (thanks @Kishfy) I had not thought of, use Ruby.  There is a great open-source project named S3Nukem which its sole purpose is to remove Amazon S3 buckets.

S3Nukem

This is an open source project hosted on Github.   Installation and setup is pretty simple (from the Github repo readme), install required gems.

For Ruby >= 1.9:

sudo gem install dmarkow-right_aws --source http://gems.github.com

The docs don’t mention it but I needed to install the right_http_connection gem, the above command fails unless it is installed.

For Ruby < 1.9:

sudo gem install right_aws

Install S3Nukum:

curl -O http://github.com/lathanh/s3nukem/raw/master/s3nukem

Make it executable:

chmod 755 s3nukem

This is done in the directory where the above curl command was executed from.

Usage:

Usage: ./s3nukem [options] buckets...

Options:
    -a, --access ACCESS              Amazon Access Key (required)
    -s, --secret SECRET              Amazon Secret Key (required)
    -t, --threads COUNT              Number of simultaneous threads (default 10)
    -h, --help                       Show this message

Running the application in a terminal window shows large numbers of files being deleted:

s3nukem

This script is fast.  I tried running this under both Ruby 1.8.7 and 1.9.2 with 1.9.2 quite a bit faster.  I didn’t run any benchmarks but it was noticeably faster, my goal was really to just delete large amounts of files.  Ruby 1.9.2 thread handling really shines here and with the ability to control the number threads from the command line, is really nice.

The nice thing about this script version is the cap on the number of items to be deleted each time, 1000 * thread_count, which defaults to 10.  With this limit in place the script won’t chew up all your system memory. 

This script is designed to delete an entire bucket but could be modified to just remove the content or a directory tree within the bucket.  I may do this for a project I am working which has a need for such functionality.

Interviewed about IronRuby

I was recently interviewed by Mike Pontacooloni of SearchWinDevelopment.com for an article about IronRuby and how it may be used by developers.  I was asked about IronRuby since I use both .NET, IronRuby and Ruby on Rails in my day-to-day work and Mike thought I might have some insight into how .NET developers would likely use IronRuby to supplement their .NET toolbox.

I think the article gives some good perspectives by a number of .NET and Ruby developers.

Mike and I had a discussion a few weeks ago and the article was published today.  Please give it a read.

Technorati Tags: ,

Running Rails 2.3.x on IronRuby

There have been some interesting discussions recently on Twitter about IronRuby and Rails.  The IronRuby team has been plodding along and with IronRuby 1.0 RC2 out I wanted to see if it could truly run a Rails application.

In case anyone does not know what IronRuby is, it is a project from Microsoft to bring Ruby into the .NET platform.

Installing IronRuby

Installation of IronRuby is pretty straightforward using the MSI installer from Microsoft available on Codeplex.  The installation is just like any Windows installer, follow the prompts and when complete IronRuby binaries should be in your path, something like C:\Program Files\IronRuby 0.9.4.0\bin.  Notice the version, 0.9.4, odd for a 1.0 RC2.  The installation says the same:

IronRubyRC2Install

I installed IronRuby and looking at the directory of the IronRuby binaries, I see all commands are preceded by an ‘i’.  So for those familiar with Ruby-related commands we get igem, irake, iirb and etc, not a big deal but something that needs to be remembered.  There is not a Ruby.exe either, but rather an ir.exe which we use to execute commands.  Also note that RubyGems comes bundled with IronRuby, no need to install this ourselves, which is nice.

Installing Rails

Installing Rails is not hard but make sure IronRuby is in your path and install with the following command:

igem install rails

This installs all dependencies and documentation.  It is interesting to note that we aren’t left with the normal (if you are familiar with Rails on OS X or Linux) rails command but rather irails.  In order to find the installed Rails version we type:

irails –v

We should see Rails 2.3.5 as a result.  I find it interesting Microsoft trying to create a Ruby which developers want to use, yet deviate the way command are run.  Maybe it will change in the official release.

Creating a Rails Application

Creating a Rails application under IronRuby is pretty much the same as on any platform with the exception of the ‘i’ in front of the command.  I decided to just create a throwaway application called ‘testapp’, just to prove Rails worked.   The command:

irails testapp

Runs and throws up a bunch of files created.  No magic here, but found some interesting things when trying to run the application.

Running the Rails Application

The default database these days used by Rails 2.3.x is SQLite3 and use this most of the time when building applications since it just works and I don’t need to deal with MySQL or PostgreSQL.

I grabbed the latest sqlite3 binary and DLL’s from the SQLite web site where you can download precompiled binaries for Windows.  I put the contents of the two zip files in the IronRuby bin directory.  Any location in your path should work.

Normally we need to install a gem named ‘sqlite3-ruby’ which is our Ruby driver for the sqlite3 database.  Doing so under IronRuby results in a fine installation but a failure when accessing our development.sqlite3 database, creating in particular.  Running the command to create our development database:

irake db:create

Provides a nice error ‘no driver for sqlite3 found’.  Well, this is an interesting problem I was happy to not have to search very long to resolve.  It seems some has forked the original sqlite3-ruby project on GitHub and created sqlite3-ironruby.  A quick:

igem install sqlite3-ironruby

Does the trick by retrying the irake db:create command and we are in business.  Our last step to prove Rails works with IronRuby is running our WEBrick server from within our ‘testapp’ directory:

ir script/server

The server starts and loads up our little test application.  Those of use used to running Ruby on most platforms are used to just using script/server without the ‘ir’ in front of it or maybe using the ‘ruby’ command with it, ‘ir’ is your ‘ruby’ and you need to precede your commands with it to ensure you have the the right Ruby binary.

If all things go well, popping open a browser and putting http://localhost:3000 in your address bar should give you a running Rails application:

IronRubyApp

Granted, it doesn’t do anything but it is a start and proves it loads.  I created some models and controllers and the ir script/generate commands worked like a charm.  All commands seemed to run as fast as, if not faster, than those in MRI 1.8.6. 

IronRuby has come a long way and we may see some production Rails applications running in IIS7 before too long.

Ruby on Rails 3 Beta Setup Hurdle

The Ruby on Rails 3 beta was released recently and has been in development for the past year, longer if you take into account Merb.

I decided I wanted to start playing around with the release for a few reasons:

  • In order to see what issues developers may face moving to Rails 3 with existing applications.
  • I wanted to see the new architecture changes from Rails 2.x
  • I also wanted to see first-hand creating a simple application and all that is involved.

There are plenty of tutorials about how to setup Rails 3 and I won’t go into details here but wanted to share the method I used and one particular error I received and how I resolved it. Jeremy McAnally has some great coverage of using Rails 3, both new projects and upgrades. His rails_upgrade gem is a great place to start when beginning to look at moving an existing Rails project to Rails 3.

Setup

I decided to use the awesome Ruby Version Manager (RVM) to manage testing Rails 3 on different flavors of Ruby. The first thing to know is Rails 3 requires Ruby 1.8.7 and above, so no 1.8.6.

Ryan Bates has a great intro to setting up Rails 3 with RVM in his latest Railscast titled Rails 3 Beta and RVM.

I decided to use Ruby 1.8.7 for initial testing. There are a bunch of gem dependencies when working with Rails 3, as you might expect. There is a gem called rails3b which installs the necessary dependencies in one swoop. These two command should do the trick:

gem install rails3b
gem install arel --pre

After these commands finished and I closed and reopened my terminal prompt, a quick rails command gave me the following error:

/usr/local/lib/ruby/site_ruby/1.8/rubygems.rb:827:in `report_activate_error': Could not find RubyGem rails (>= 0) (Gem::LoadError)
from /usr/local/lib/ruby/site_ruby/1.8/rubygems.rb:261:in `activate'
from /usr/local/lib/ruby/site_ruby/1.8/rubygems.rb:68:in `gem'
from /usr/local/bin/rails:18

Some Googling did not return any usable results from anyone with this error. I really didn’t expect anything, things are just too new. Thinking back to another way to install Rails 3, I decided to try this instead:

gem install tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n
gem install rails --pre

After running these two gem commands the new rails command works as expected. I’m not really clear what the difference was which fixed the rails command, but I don’t know if I need to.

Do keep in mind the default database provider is Sqlite3 so you need to install that gem (sqlite3-ruby). Probably one of the biggest tips is to make sure you don’t use sudo when installing gems under RVM managed Ruby installation, just use gem install <gem name>.

UPDATE: Jeremy McAnally points out the rails3b gem installs the dependencies for the Rails 3 beta, not Rails itself.  This would certainly explain why my initial attempt failed and only worked after INSTALLING RAILS.

Technorati Tags: ,

Patching Ruby on Rails Refresher

UPDATE: As one comment points out, it is not a good idea to directly patch production unless it was an emergency.  The normal state of patching would be to patch the source and make sure your tests still pass and likely to test on a staging environment.  The process to patch would still be the same as I describe below.

The recent XSS Vulnerability in Ruby on Rails discussed on the Ruby on Rails blog and discovered by Brian Mastenbrook, reminded me about patching my Rails applications which are running vendored.  If not doing this all the time, one can forget how it is done.

All of my production Rails applications keep a copy of Rails in the <application_root>/vendor/rails directory.  This just keeps me in check that I don’t upgrade Rails on a server and possibly break a production application.   The only minor drawback to this approach is when a patch is released, as with this XSS Vulnerability, you have to manually update the Rails installation for each application by hand.  If you don’t do it all the time, one can forget how it’s done.

Patching Rails

Getting and applying a patch is pretty simple.  The list of patches are listed as:

Follow 3 easy steps:

  1. cd <your_application_root>/vendor/rails
  2. wget http://weblog.rubyonrails.org/assets/2009/9/4/2-2-CVE-2009-3009.patch
  3. patch -p1 < 2-2-CVE-2009-3009.patch

You need to know the Rails version you are running vendored before you can determine which patch file to apply.  The simple way for me is to run script/about from <your_application_root>.  This displays the Rails version which you can then choose from the URL links above and replace the URL you need for the #2 wget command.

Depending on the security settings where the application is installed, the wget and patch may need to have a sudo inserted before the command.  I needed to do this my production servers but it would not be needed if patching a local project which would be later committed to source control.