Oh, the memories

Ruby 7 Comments »

Let’s pretend that you’re busy making a kick ass template maker, and you’d like to keep backups of the file you generate. You certainly don’t want to write over it every time, in case there’s customer changes that have been made since the last time you did. What if you want to keep 5 copies of it, and only 5?

Rather than code it all yourself, save yourself some trouble and download the Backup gem off github, and you’re ready to go:

Install

  $ sudo gem sources -a http://gems.github.com
  $ sudo gem install engineyard-backup

You only need to install the source once and then you can install any gem hosted on github, which basically means any repository that has a .gemspec at the root of their repository.

Usage

  backup = Backup.new("/the/file/to/backup")
  backup.run

So what exactly have we done here? Well, we’ve made a copy of the file we wanted backed up, and we’ve added a timestamp to it. Every time we run this file, Backup will move the current file to a timestamped version, and also ensure that (by default) 5 versions of that file are kept.

Want a different number of ‘releases’?

  # Set a different amount of backups on initialize
  backup = Backup.new("/the/file/to/backup", 10)
  # or set it manually
  backup.backups = 15
  # Run the backup
  backup.run

Some more methods:

  backup = Backup.new("/the/file/to/backup")
 
  # which files would we keep in a backup
  backup.keep_list
  # => ["backup.20080430185243", "backup.20080430185246", "backup.20080430185243", "backup.20080430185250", "backup.20080430185254"]
 
  # which files would we delete in a backup
  backup.delete_list
  # => ["backup.20080430185221", "backup.20080430185224", "backup.20080430185230"]
 
  # how about skipping the cleanup?
  backup.run( :no_delete )
 
  # what if we just want to cleanup the old revisions
  backup.cleanup
 
  # and finally, how about we just get a list of the backup files present
  backup.find_all_releases

Notes

This library doesn’t care where it’s being used, it could be a Rails application or a command line Ruby script of some sort. It merely handles backups of files in the form of a library. If you just want to backup some files and not programmatically from within your own application, then these are not the droids you are looking for.

Conclusion

Easy peasy, lemon squeezy backups. Enjoy.

Famous Characters Using Ruby

Development, General, Ruby 3 Comments »

So, it turns out both Eric Cartman and Arnold Schwarzenegger like Ruby! Who’d have known!

Eric Cartman
Arnold Schwarzenegger

There’s rumoured to be Borat, Ali G and possibly Bruce Forsyth coming too, in an extended version of the question!

RailsConf 2008 (Portland) Talk Proposal Accepted

Ruby on Rails No Comments »

So, my talk proposal “Hosting and the Woes” just got accepted, in a nutshell it’s all about hosting Rails and the problems you come across. It will also have a questions and answers section at the end which will be hosted by a few Engine Yard members (Ezra Zygmuntowicz, Tom Mornini, Taylor Weibley, Corey Donohoe if he wants, and more).

Keep your eye out for updates, I’ll let you know confirmed attendee’s at a later date.

Irish Web Tech Conference (IWTC)

Ruby on Rails 5 Comments »

In case any of you are going to the Irish Web Technology Conference in Dublin which starts today and lasts until the end of the week, I’ll see you there! I’m doing a Ruby on Rails intro talk tomorrow (Wed 27th Feb) at 15:15.

Also note, it could be awful, I’m trying a new presentation style…lots of short, extremely large words, I believe it’s called the “Takahashi Method”. Here’s to falling flat on your face!

<update>

The new presentation method worked well, although I didn’t follow the pattern strictly, my slides are available in various formats here:

HTML | Flash | Quicktime | PDF

Even Faster Sessions

Ruby on Rails, Snippets 3 Comments »

Most of you will know by now, that ActiveRecord isn’t the fastest ORM on the planet, so why use it for storing session data in your database? Plan A would be to flip over to SqlSession, which bypasses the ActiveRecord method and goes straight to the database. That’s fine for most sites, but what about those really high traffic sites?

Alexey Kovyrin (for scribd.com) has written the ultimate solution, FastSessions. FastSessions uses some clever MySQL (no, it’s not agnostic) tricks to make for real speedy session storing and lookup. Now I’m no database guru, but this plugin is by one of the MySQL Performance Blog fella’s so you can be sure that it does exactly what it says on the tin.

Installation and use is easy as pie:

  piston import http://rails-fast-sessions.googlecode.com/svn/trunk/ vendor/plugins/fast_sessions

Rails environment configuration:

  config.action_controller.session_store = :active_record_store

Set up your migration to create the table:

  ./script/generate fast_session_migration AddFastSessions

Run the migration:

  rake db:migrate

Little tricks like not saving the session data back to the database unless it changes, or is not empty, make for a huge saving over time.

Read more about it here: http://code.google.com/p/rails-fast-sessions/.

Simple AJAX and Inline Javascript with Rails

Ruby on Rails 3 Comments »

I’ve noticed a lot of people asking questions about ajax, rjs, scriptaculous and other whizzy cool effects lately. So I thought I’d document a couple here so there’s less confusion about some of the simpler effects. I’ve included an element toggle on a hyper link, a simple div that updates with data from an action using linktoremote, and others. Enjoy.

This article is re-posted, from my old blog which will be removed in time.

You’ll learn effects like these: Video of ajax effects. Let’s continue…in the style of Gordon Ramsey:

Prepare

All of these examples assume you have included the default javascript files in your application.rhtml file:

<head>
  <%= javascript_include_tag :defaults %>
</head>

Toggle

The first of our simple effects is going to have to be the simple toggle (hide/show) of a div element. There is no remote call used in this, it simply uses javascript (generated by our ruby code) to show and hide a element of our choice.

<%= link_to_function "toggle with my div", "Element.toggle('to_toggle')" %>
<div id="to_toggle">
  Now you see me, now you don't!
</div>

Remote

Next we’re going to fire an action from a linktoremote and then update a list of items on the page, this involves multiple code pieces in different files, keep up.

<!-- app/views/words/index.rhtml -->
<ul id="sentence">
  <li id="word_1">baby</li>
  <li id="word_2">unzip</li>
  <li id="word_3">my</li>
</ul>
<%= link_to_remote "WHAT?!?", :url => { :controller => 'words', 
                                        :action => 'update' }, 
                              :loading => "Element.show('loading')" %>
<div id="loading" style="display:none;">Loading...</div>
 
<!--  app/controllers/words_controller -->
def update
  @word = "laptop bag!"
  return if request.xhr?
end
<!-- app/views/words/update.rjs -->
# hide the loading text
page.hide 'loading'
# insert a new li into the element with an id of sentence
page.insert_html :bottom, 'sentence', 
  "<li id='word_4'>#{@word}</li>"

Notice how we use the same name for our rjs file as we did for the action we called, and then we ask the controller to return if the request was an xml http request (which is what ajax uses). This way if we want to do both rjs and standard requests with the update action we can.

I also demonstrated the use of a loading div here, but you could use a loading image as well, like a spinny circular thing or dots…or whatever takes your fancy.

Highlight

Let’s modify the above example to highlight the new element when it arrives, this one’s far too easy. Add this to the bottom of update.rjs:

page.visual_effect :highlight, 'word_4', :duration => 3

Now when the element is added, you’ll have your attention drawn to it. The duration can be left off because it’s optional and defaults to 2 seconds, I just wanted to make you aware that it’s there.

Blind

Again, modify our existing call and make it slide down instead of just appear, change the update.rjs to this:

# hide the loading text
page.hide 'loading'
# insert a new li into the element with an id of sentence
page.insert_html :bottom, 'sentence', 
  "<li id='word_4' style='display:none;'>#{@word}</li>"
page.visual_effect :blind_down, 'word_4', :duration => 2

We added to our li item a style of display, and set it to none. This is standard inline css markup, so when the item is added to our page it’s hidden. Then we use the blind_down visual effect to slide it down with a duration of 2 seconds.

Simmer

I hope this helps all the ajax beginners get started with effects you can play with, be sure to check out the Rails api documentation for more scriptaculous effects.

Any questions boys and girls?

Filtering passwords in the rails log

Snippets No Comments »

Every time a user logs on to your Rails site, they enter a username or password. The login form you’ve created no doubt POST’s that value to your Rails application, which it then kindly logs in your production.log. This is fine for development, but what about when you deploy your site to your production environment? That’s right, for however long you store your logs (I’ve seen some customers keep 3+ years worth of logs), those user passwords will be sat in that log. This isn’t the most secure way of handling this. Rails is set up to be able to filter these though, but how? Use the following snippet to instruct your Rails application to filter any parameters called ‘password’:

  class ApplicationController < ActionController::Base
    filter_parameter_logging "password"
  end

Apple’s Leopard REXML Bug

Ruby, Ruby on Rails 2 Comments »

Just in case any of you wonder why when you use REXML’s write method on ruby 1.8.6 (2007-09-24 patchlevel 111) [universal-darwin9.0] and possibly other versions, you get errors, it’s a bug in Apple’s REXML library. See this:

def write(writer=$stdout, indent=-1, transitive=false, ie_hack=false)
  Kernel.warn("#{self.class.name}.write is deprecated. See REXML::Formatters")
  formatter = if indent &gt; -1
    if transitive
      REXML::Formatters::Transitive.new( indent, ie_hack )
    else
      REXML::Formatters::Pretty.new( indent, ie_hack )
    end
  else
    REXML::Formatters::Default.new( ie_hack )
  end
  formatter.write( self, output )
end

As you can see, the method sets a local variable of ‘writer’ in the method arguments, however at the bottom it uses ‘output’. A simple change of the bottom line fixes it:

  formatter.write( self, writer )

For those who requested it, here’s how to use the formatter:

  # I want to create a REXML document to output
  require "rexml/document"
 
  # Make a pretty formatter
  formatter = REXML::Formatters::Pretty.new( 2 )
 
  # Create some silly xml example
  xml = REXML::Document.new '<moo>RAR!</moo>'
 
  # Write to STDOUT
  formatter.write( xml, $stdout )
 
  # Write to file
  xml_file = File.open( "some_file.xml", "a+" )
  formatter.write( xml, xml_file )

Shifted to Wordpress

General 4 Comments »

I figured it was time I spent some time on my blog, and move to Wordpress.  It’s easier to maintain than mephisto, and there’s more support/plugin support for it.

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in