Using Rails’ Flash Messages with AJAX Requests

Have you ever wondered how to get access to the Ruby on Rails' flash message when performing a AJAX or restful web request?  You might hit yourself on the head when you discover how easy it is.  Simply append the flash message to the Response headers.  You could even wrap this in a helper, and using an after_filter to automatically add the header for you on every AJAX response.

class ApplicationController < ActionController::Base
after_filter :flash_headers
 
def flash_headers
  # This will discontinue execution if Rails detects that the request is not
  # from an AJAX request, i.e. the header wont be added for normal requests
  return unless request.xhr?
 
  # Add the appropriate flash messages to the header, add or remove as
  # needed, but I think you'll get the point
  response.headers['x-flash'] = flash[:error]  unless flash[:error].blank?
  response.headers['x-flash'] = flash[:notice]  unless flash[:notice].blank?
  response.headers['x-flash'] = flash[:warning]  unless flash[:warning].blank?
 
  # Stops the flash appearing when you next refresh the page
  flash.discard
end

And then you just read the header with whatever you happen to be reading it with. For completeness sake here is an example of how to read the header in JavaScript using Prototype:

 new Ajax.Request('/your/url', {
  onSuccess: function(response) {
    var flash = response.getHeader('x-flash);
    if (flash) alert(flash);
 }
});

Forget the UML Module for NetBeans!

A while ago, I wrote a blog post on how, with considerable effort, you can get a native UML NetBeans module up and running despite the NetBeans UML module being removed from the standard distribution.

I managed to get mine working, but there is a huge cost - Once you close the project (or the IDE) housing the diagram, you can never reopen it.  Out of pure determination desperation and perseverance I managed to get the diagram I needed, printed and done; but I can never open it and make adjustments.

Apparently, we're all supposed to use SDE for NetBeans by Visual Paradigm now as the "official" replacement, but I tried it, and it was simply fail.  Proprietary and fail.

Fortunately, after taking a punt, I found a UML modelling tool which is not only more functional and better than the NetBean's module was, but looks better too.  It even has the ability to create code from class diagrams (which you can obviously just cut and paste into your NetBeans IDE project of choice.  Its called ArgoUML.

ArgoUML is the leading open source UML modeling tool and includes support for all standard UML 1.4 diagrams. It runs on any Java platform and is available in ten languages.

I've used it a bit now, and I just love it.  I particularly like the way it can make recommendations on how to improve your diagram using its "critics" system.

It's features boast:

  • All 9 UML 1.4 Diagrams supported
  • Platform Independent: Java 5+
  • Click and Go! with Java Web Start
  • Standard UML 1.4 Metamodel
  • UML Profile support with profiles provided
  • XMI Support
  • Export Diagrams as GIF, PNG, PS, EPS, PGML and SVG
  • Available in ten languages - EN, EN-GB, DE, ES, IT, RU, FR, NB, PT, ZH
  • Advanced diagram editing and Zoom
  • OCL Support
  • Forward Engineering
  • Reverse Engineering / Jar/class file Import
  • Cognitive Support
    • Reflection-in-action
      • Design Critics
      • Corrective Automations (partially implemented)
      • "To Do" List
      • User model (partially implemented)
    • Opportunistic Design
      • "To Do" List
      • Checklists
    • Comprehension and Problem Solving
      • Explorer Perspectives
      • Multiple, Overlapping Views

I haven't yet worked out how to create object instances from my class diagrams yet, so I'm not sure if it just doesn't support this or it's user error, but in every other conceivable way, it seems to be an excellent UML modelling application for virtually every OS you can name.

Guess What’s Coming to OSX Tomorrow?

Optimizing Apache 2 Configuration for Smaller VPS Instances

I recently down-scaled the server which hosts this blog (one among a few). Being a Ubuntu server, it was trivial to install the LAMP stack, including Apache 2. However, I quickly discovered a problem with the default configuration on a server with a lesser amount of memory (in this case 512MB). The server would work just fine for a short while and then grind to a near halt, where even a SSH session becomes unusable. When I eventually got into the server, I listed the processes and found the 'apache2' process running several dozen times!

The default configuration for the Pre-fork MBM (Multi-Processing Module) reads as follows:

# prefork MPM
<IfModule mpm_prefork_module>
   StartServers          16
   MinSpareServers       16
   MaxSpareServers       32
   ServerLimit           400
   MaxClients            400
   MaxRequestsPerChild   10000
</IfModule>

To something more reasonable to a server with limited memory, such as:

# prefork MPM
<IfModule mpm_prefork_module>
   StartServers         4
   MinSpareServers      4
   MaxSpareServers      8
   MaxClients           35
   MaxRequestsPerChild  10000
</IfModule>

I found this has made my server much more stable - and I've not noticed any performance decrease from the new configuration.

Ruby Code to Scrape Images from TwitPic URLs

Twitpic logo

I've been trying to find an easy way to re-grab my TwitPic images back off TwitPic to be re-syndicated on a communal family website I am trying to create.  I found a great site which had some Rails code that scraped the image, so I took the code and modified it to make it compatible for pure Ruby (too be honest it didn't need much modifying at all) .

Here’s my modified snippet of code that I’ve been using to grab the image from Twitpic with the Hpricot gem:

 
require 'rubygems'
require 'net/http'
require 'hpricot'
 
def rip_twitpic(url)
  begin
    code=url.match(/[\w]+$/).to_s
    unless code.empty?
      uri=URI.parse(url)
      resp=Net::HTTP.get_response(uri)
      html=Hpricot(resp.body)
      html.at("#photo-display")['src']
    end
  rescue Exception => e
    puts "Error extracting twitpic: #{e}"
    url
  end
end

Just as it appears, this method will return the URL of the image embedded on the page that the TwitPic URL points too.

This will form the core part of a little project which will allow you to scrape TwitPic images and send them to a server of your choosing. I'll try to release this ASAP but in the meantime, I thought a few of you might find this useful. I know I do.

Getting SSI to work in MAMP

It's no secret that I adore my Mac, mostly because it just makes my life easier.  I enjoy the security of OSX, I love it's responsiveness and I love that my operating system doesn't punish me for installing applications and development stacks just to 'play with them'.  A while ago, while looking for a stack that would let me quickly and effortlessly get Apache, MySQL and PHP5 working together without having to muss about with configs and the such, I discovered MAMP and frankly, I adored it instantly.  After a rather large download, it was effortless to install and running it was a cinch.  And better still, the server applications only run when you open the MAMP application and tell them to run, so that you dont loose vital system resources running services you dont need.

Additionally, my IDE of choice, NetBeans can integrate directly with MAMP, so that when you create (for sake of argument) a new PHP project and run it, it automatically puts the project files into the MAMP Apache directory (to be honest you do need to configure the path when you create the project, but its no big deal) making development painless and convenient.

But I did hit a snag recently when for a university assignment I was required to do a XHTML website using HTML Server Side Includes.  I was shocked when I ran my website and my SSI didnt work.

But there is a solution.

To make .shtml work, I deleted the comment-symbols ( # ) in the file http.conf (find it in /Applications/MAMP/conf/apache/ and at the time of writing was near lines 982:

# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
AddType text/html .shtml
AddOutputFilter INCLUDES .shtml

High Performance & Multi-threaded SCP Using RSYNC

Recently, I had the somewhat laborious job to backup a stack of websites and blogs from my remote web server.  Initially I tried do it with a simple SCP command; but after letting it run for about an hour, it was obvious that it was just too slow and taking too long downloading each file one at a time.

After talking complaining to a friend he suggested using the RSYNC command. Surprisingly it was incredibly very easy to get it working, you simply issue:

 rsync -avz -e ssh remoteuser@remotehost:/remote/dir /this/dir/

Obviously changing the appropriate parts for your case.

I found it to be at least 10 fold faster (or more) than SCP on it's own, and better still, RSYNC will resume when SCP wont!  Try it and see for yourself.

Project Euler Problem 52 Solution

It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.

Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.

My solution in Ruby:

i = 1;
answer = nil;
 
while answer == nil
  i += 1
  x = i * 2
  base = Array.new(x.to_s.scan(/./))
  matchbase = true
  for t in 3..6
    break if matchbase == false
    x = i * t
    digits = Array.new(x.to_s.scan(/./))
    digits.each { |d| matchbase = false if base.index(d) == nil }
  end
  answer = i if matchbase == true
end
puts "Answer: #{answer}"
 

Left4Dead and Left4Dead 2 Available on OSX in October

Back in March, the Mac gaming world got excited when Valve announced their Steam gaming software was coming to the Mac -- along with Left 4 Dead 2, Team Fortress 2, Counter-Strike, Portal, and the Half Life series.  I was shocked at just how quickly the Valve catalog was being ported to OSX, but then, the announcements stopped as suddenly as they started; alegedly sue to a number of graphics and OpenGL bugs issues that Valve helped Apple sort out.  Today, I found this little gem:

We’d previously heard tell that now that those graphic issues are fixed, Valve as hard at work to bring Left 4 Dead and Left 4 Dead 2 to OS X by October… and now, if a casual mention over at Macworld is anything to go by, it looks like that date might have been further locked down to October 5th, along with the latest Left 4 Dead and Left 4 Dead 2 add-on pack, “The Sacrifice.”

So only a few more sleeps until all Mac users can help keep the hordes of zombies at bay with their Windows buddies.

Do I Look Like I’ve Lost Weight?

I've been on a new diet recently, and it's had really good results.  I started out 123.8Kg and a little over a month later, as of today, I'm down to 111.9Kg.

Now obviously by the numbers, this is a great result, but the sad fact is that I dont feel different.  I dont feel like I  look different either, despite what friends and family have  said.  I'm wondering if being obese (that word cuts like a knife, doesn't it?) effects you psychologically more than we think.  This then, after loosing 10cm off my stomach circumference, which should be clearly obvious - just isn't to  me in the mirror.  I wonder if I might have some kind of body image problem, or worse still, a kind of eating disorder?

I like to think that I am a level-headed person, but over the past 3 or 4 years I've been becoming increasingly self-conscious about my body - to the point that I no longer go swimming!  I'm not really sure what to do from here, but since this diet has been working, I guess I'll just keep doing it, and hopefully, when my current clothes simply do not fit any longer, I'll feel differently.