more info

Media72 Hosting Articles and Tips

Archive for the 'Ruby on Rails' Category

New mod_rails hosting packages available today

Thursday, May 1st, 2008

Media72 are pleased to announce the immediate availability of mod_rails driven Ruby on Rails hosting packages. Mod_rails, or Phusion Passenger as it is also known, has been gaining a lot of attention recently, and rightly so. It's a huge step forward for the Rails hosting community in terms of application deployment and management. Many big names in the industry such as David Heinemeier Hansson and Yukihiro Matsumoto (Matz) already have good things to say about mod_rails. Mod_rails vastly simplifies Ruby on Rails deployment, no longer will you have to mess around with .htaccess files or deal with fastcgi fickleness. Deployment can be as simple as uploading your rails application then loading it in your browser. And restarting your application is achieved by simply creating a text file called restart.txt in your rails tmp directory, what could be more simple? Our customers are already enjoying the benefits of mod_rails and we are one of the only hosts in the UK to offer support for mod_rails at this time. All of our rails accounts are hosted in our well connected London data centre which means fantastic speeds around Europe. Using Media72 you will also enjoy better search engine rankings with the UK engines when compared to hosting elsewhere. Why not take a look at our comprehensive range of mod_rails based packages? Prices start from only £7 a month.

Howto: Write a plug-in

Wednesday, January 16th, 2008

In my previous post, I listed 6 things that you should try in Rails. I also promised some example code to get you started. Since I have already covered installing and upgrading rails, the next cab off the rank is writing a plug-in.

Plug-ins are fantastic - they allow you to abstract away common code into nice little bundles that you can re-use on other projects. Rails even has a built-in system for downloading other peoples plug-ins straight from their SVN repository. With the change over to Rails 2.0, some used-to-be-core functionality has been moved into plug-ins, to clean up the core tree and to allow other developers to release new versions of the plug-ins outside of the regular Rails release cycles.

In this (very brief) tutorial, we will create a plug-in called acts_as_blabbermouth that will print out random quotes . Obviously this plug-in is of little use in the real world, but it should act as a nice demonstration of how plug-ins work.

It’s really easy to generate the boilerplate code thanks to the generate script. To start your plug-in, run the following command in the root of your Rails app:


script/generate plugin acts_as_blabbermouth

You should see an output similar to this:


create  vendor/plugins/acts_as_blabbermouth/lib
create  vendor/plugins/acts_as_blabbermouth/tasks
create  vendor/plugins/acts_as_blabbermouth/test
create  vendor/plugins/acts_as_blabbermouth/README
create  vendor/plugins/acts_as_blabbermouth/MIT-LICENSE
create  vendor/plugins/acts_as_blabbermouth/Rakefile
create  vendor/plugins/acts_as_blabbermouth/init.rb
create  vendor/plugins/acts_as_blabbermouth/install.rb
create  vendor/plugins/acts_as_blabbermouth/uninstall.rb
create  vendor/plugins/acts_as_blabbermouth/lib/acts_as_blabbermouth.rb
create  vendor/plugins/acts_as_blabbermouth/tasks/acts_as_blabbermouth_tasks.rake
create  vendor/plugins/acts_as_blabbermouth/test/acts_as_blabbermouth_test.rb

As you can see, all of the boilerplate code has been created in the vendor/plugins/acts_as_blabbermouth directory.

The README and MIT-LICENSE are just generic text files that you should fill out - generally, the README file is the first place a new user will look for instructions on the plug-in.

The lib directory will hold the guts of your plugiin. The tasks directory is a place where you can store any rake tasks that your plug-in might need. The tests directory is, well, pretty self explanatory - just as you can test your Rails app, you can test your plug-in too. The install.rb and uninstall.rb files are called when installing and uninstalling your plug-in - you can place code here to initialize your environment and to cleanup after yourself. Finally, init.rb is the file that Rails actually calls to load your plug-in.

The main file we have to worry about is /lib/acts_as_blabbermouth.rb - this is where our main code will go.

Firstly, we need to include the acts_as_blabbermouth.rb file into the environment. This is done by adding the following line to the init.rb file:


require File.dirname(__FILE__) + '/lib/acts_as_blabbermouth'

Next, we add the following code to lib/acts_as_blabbermouth.rb


# ActsAsBlabbermouth
module ActiveRecord #:nodoc:
  module Acts #:nodoc:
    module Blabbermouth #:nodoc:
      def self.included(base)
        base.extend(ClassMethods)
      end

      module ClassMethods
        def acts_as_blabbermouth
          include ActiveRecord::Acts::Blabbermouth::InstanceMethods
          extend ActiveRecord::Acts::Blabbermouth::SingletonMethods
        end
      end

      module SingletonMethods
        def quote_me
          quotes = [
            "When you come to a fork in the road, take it. -Yogi Berra",
            "Every child is an artist. The problem is how to remain an artist once he grows up. -Pablo Picasso",
            "What we anticipate seldom occurs; what we least expected generally happens. -Benjamin Disraeli",
            "Drive-in banks were established so most of the cars today could see their real owners. -E. Joseph Cossman",
            "The greatest pleasure in life is doing what people say you cannot do. -Walter Bagehot"
          ]

          quotes[rand(quotes.size)]
        end
      end

      module InstanceMethods
        def quote_me
          self.class.quote_me
        end
      end
    end
  end
end

ActiveRecord::Base.send(:include, ActiveRecord::Acts::Blabbermouth)


Now, create a model file called quote.rb by running


script/generate model quote

and add the following line after the class declaration and before the end declaration


acts_as_blabbermouth

Fire up the script/console and type:

Quote.quote_me

Voila! If all went to plan, you should see one of the random quotes. Congratulations! You just wrote a plug-in!

So how did we do it?

  1. We drilled down in to the ActiveRecord::Acts module and mixed in a module called Blabbermouth. This acts like a namespace in other languages, so we can create our own set of classes and methods without stomping on other peoples plug-ins.
  2. We override the included class method, which gets called when the plug-in gets mixed in to another module. Here, we include the ClassMethods module, which exposes the acts_as_blabbermouth method to the model class
  3. We define the acts_as_blabbermouth method. All this method does is include the InstanceMethods and SingletonMethods modules. The InstanceMethods module contains all of the methods available on an instantiated object and SingletonMethods contains all the methods available to the un-instantiated class.
  4. We create a SingletonMethod called quote_me, which returns the random quote. This can be called by calling Quote.quote_me. We also create a method called quote_me in the InstanceMethods module, which calls the SingletonMethod - this way both the class and the object can call the quote_me method.
  5. Finally, we call ActiveRecord::Base.send(:include, ActiveRecord::Acts::Blabbermouth) which tells the ActiveRecord::Base module to include the code we have written.

For those of you playing at home, I’ve attached the plug-in source in a tarball, so you can get a better idea of how it all fits together. So off you go, go and create a plug-in yourself!

This article provided by sitepoint.com.


Learning Ruby on Rails Fundamentals Without Reading

Wednesday, January 9th, 2008

For all those people, like me, who would rather listen or watch something than read there is now the perfect way to learn Ruby on Rails. Building Web Apps has a new podcast called Learning Rails by Michael Slater and Chris Haupt. It starts at the very beginning teaching you the most basic things about Rails so is perfect for anyone that has no prior Rails experience. They have only got to episode 4 so far but I would assume they will keep going and progress to more advanced topics as time goes on, they say there will be a new episode every 2 weeks. The podcast focuses on the concepts behind Ruby on Rails rather than trying to tech coding. I highly recommend the podcast to anyone new to rails.

6 things to try in Rails this year

Wednesday, January 9th, 2008

It seems that blog posts in the first couple of weeks of the new year (happy new year by the way) follow the “x things to do this year” meme as a virtual homage to new years resolutions. Never one to buck a trend, I have prepared this short list of things you should try in Ruby and in Rails - I hope to cover each topic in more detail over the next couple of weeks.

  1. Install Rails: This is aimed at those of you out there that haven’t tried Ruby on Rails yet. Jump in - have a go, there are plenty of resources out there, and it is fairly easy to install regardless of your platform
  2. Upgrade to Rails 2.0: I have covered what’s new in Rails 2.0 in a number of my previous posts, and upgrading isn’t really THAT difficult if you follow the steps and fix any deprecation notices.
  3. Write a plugin: Plugins allow you to re-use common patterns without having to resort to the dreaded cut-and-paste keys. Rails has a built in plugin generator that gives you the skeleton code, all you need to do is to mix-in the right modules - oh, and write the code…
  4. Try out RESTful routes: RESTful Rails have been around for a while now, but many of the tutorials around the net are still CRUD based, so if you are a Rails beginner, you might not have tried them out yet.
  5. Use Ruby as your scripting language: Because Rails does such an excellent job of doing the hard work, it is very likely that you have never had to manually connect to a database or read the contents of a directory or performed other mundane tasks in Ruby. If you have to do any scripting, instead of PERL or Python, use Ruby - it will help you better understand the nuances of the language.
  6. Refactor your code the Ruby way: If you have come from other C-like languages (such as PHP or Java) you would
    be used to the idioms from that style of coding. Try refactoring your code to use blocks instead of for loops, or using inline if statements - you can squeeze a lot into one line in Ruby, see how far you can push it. Again, this is a great exercise to learn the language.

Go on, try them out - the new year is a great time to try something new!

This article provided by sitepoint.com.


Flexible Fixtures in Rails 2

Wednesday, December 12th, 2007

As Matt Magain pointed out yesterday, Rails 2.0 is now gold! Not a lot has changed feature wise from the PR (makes sense - features were frozen at that point), although it seems that the new improvements to fixtures managed to slip in to the final version.

Rather than having to map foreign keys in your fixtures using id numbers, you can use fixture names, which makes life a whole lot easier. So you can now write:

users.yml

joe_blogs:
  id: 1
  first_name: Joe
  last_name: Blogs
mary_smith:
  id: 2
  first_name: Mary
  last_name: Smith


websites.yml

website_1
  id: 1
  user: joe_blogs
  url: "http://www.joeblogs.com"

website_2
  id: 2
  user: mary_smith
  url: "http://mary.smith.id.au"

which obviously makes a lot more sense to a human reading it, especially when you have a large number of fixtures across many models.

Let me join Matt in congratulating the Rails core dev team for achieving this milestone - roll on Rails 3!

This article provided by sitepoint.com.


10 Ruby On Rails Plugins You Should Be Using

Sunday, December 9th, 2007

One of Ruby on Rails strengths is how easy it is to extend with Ruby Gems and plugins, becuase you don't have to code everything yourself you can save a lot of time. One problem facing Rails codes is knowing what plugins are out there and how to use them. The following is a list of 10 plugins that should make your coding life much easier and save you a fair bit of time.

  1. attachment_fu - Anyone dealing with file uploads, especially images, should take a look at this plugin, it's a replacement for acts_as_attachment. The plugin is easily configurable and supports storing uploaded files in the file system, database, or on Amazons S3 service. It also supports 3 image manipulation libraries for resizing and altering your uploaded images, Image Science, Mini Magick, and Rmagick.
  2. acts_as_taggable_on_steroids - Tag clouds are not particularly easy to code when you are first starting out. This plugin handles all of the heavy lifting for you including adding and removing tags and even tag cloud calculations.
  3. minus_r - If you are not keen on the prototype javascript library and want to use alternative libraries without replacing the default rails javascript helpers or want to write real javascript in your rjs templates this plugin is for you.
  4. acts_as_ferret - Powerful search plugin that fuilds on the ferret gem for enabling full text searching in your applications. Ferret is a port of Apache's Lucene and enables fast powerful searches with very little code.
  5. white_list - Is essential for any site that allows users to input html to be displayed, this plugin lets you filter out bad HTML tags and attributes to strip out unwanted code and reduce the risk of XSS attacks.
  6. acts_as_ordered - This plugin provides an easy way to find a records neighbours, great if you want to provide previous and next buttons on your site.
  7. BlueCloth/RedCloth - These two are actually gems and convert markdown and textile syntax into HTML markup.
  8. Rspec - All the cool kids are using it these days, why not jump on the fashion bandwagon too? Seriously though, Rspec is a way of specifying how your application "should" behave and then testing it actually "does" what it should.
  9. autotest - This makes testing a breeze, it keeps track of which files you are working on and automatically runs the tests for the file when you save them. When you hook this into growl you can get popup notifications that tell you if your tests passed or failed. Now you can concentrate on coding and forget about remembering to run your tests, works with Rspec and rails built in unit test.
  10. restful_authentication - This replacement for act_as_authenticated offers easy site authentication in a box.
  11. acts_as_rateable - OK we lied, this is the 11th plugin lets call this one a freebie. Add a ratings system to any model, very simple to use neat little plugin.
We hope you found this list useful, try them out and let us know what you think of them. Of course all of the plugins are fully compatible with our Ruby on Rails hosting packages.

Upgrading to Rails 2.0 how to

Sunday, December 9th, 2007

Ben Smith has written some Rails 2 upgrade notes which cover the process of upgrading and existing application to Rails 2.0. Included in the article is a rake task for checking depreciation warnings before you upgrade which is very useful.

Rails 2.0 causing startup errors for some customers

Saturday, December 8th, 2007

After upgrading our servers to Rails 2.0 it has come to our attention this has caused problems for some customers rails applications where the application will fail to start. This will happen when your application is not set to use a specific version of rails and will therefor load the most recent version of rails. On servers where customers have been affected we have removed rails 2.0. This is a temporary measure to give customers time to upgrade their applications. We will be reinstalling rails 2.0 on all servers on Friday 14th December. Read on to see how to make sure your rails application will still work after the upgrade. We are advising all customers to either specifically set the rails version to use in your environment or freeze your rails gems. To set the rails environment in your config edit the config/environment.rb file and un-comment or add the following line: RAILS_GEM_VERSION = '1.2.6' To freeze your rails gems run the following command from your rails application root: rake rails:freeze:gems This will copy all of the files needed to run rails into your vendor/rails directory. If you need to freeze to a specific version of rails run the following command: rake rails:freeze:edge TAG=rel_1-2-6 You may also need to include your other gems within your application, there is an excellent article by Chris Wanstrath called vendor everything that covers how and why you should do this. Lastly, anyone wanting to upgrade their current application to rails 2.0 should first upgrade to rails version 1.2.6 and check for any depreciation warnings before making the leap to rails 2.0. Also watch out for the code that has been removed from rails and is available in plugin form!

 

hedges