Size != Count

October 30th, 2009 by Radar

When using a has_many :through in Rails with a counter_cache an interesting thing can occur. When you call size on the association, it can return a seemingly incorrect number. This is caused by the following code in activerecord/lib/has_many_through_association.rb:

def size
  return @owner.send(:read_attribute, cached_counter_attribute_name) if has_cached_counter?
  return @target.size if loaded?
  return count
end

It’ll reach the counter_cache column which could be incorrect, giving you all the objects returned when you look up the association, but an invalid number. This was only in my tests where data was being created through Machinist. Just watch yourself for this, this is the second time it has caught me, and ideally the last.

Connecting to Multiple Databases Using ActiveRecord

October 17th, 2009 by Radar

You can call establish_connection with the key that points to another database config in your config/database.yml file

class Person < ActiveRecord::Base
  establish_connection(:hr)
end
class Ticket < ActiveRecord::Base
  establish_connection(:bug_tracker)
end

If you have a whole bunch of models that need to connect to another database:

class HR < ActiveRecord::Base
  establish_connection(:hr)
end

class People < HR
  # ...
end

class Resource < HR
  # ...
end

Fixed By Rails 3

October 9th, 2009 by Radar

Today I launched a sister site to fixedbytm2.com which is fixedbyrails3.com. Here you can list your gripes and wishes for Rails 3, as well as the new feature of being able to vote on them! Enjoy!

Banning Users Using Middleware

October 6th, 2009 by Radar

Bo Jeanes, a coworker at Mocra, recently implemented a way to ban people on one of his side projects DearQUT because somebody was posting nasty messages. We were talking earlier today about it and the topic of using a middleware came up since we “don’t want to waste resources on that asshole”. So I thought I’d investigate to to see how easy it is to make a middleware in Rails, turns out it’s very easy!. If you don’t like reading blog posts, I have sample Rails application containing the very same source code I used for this blog post. This contains also the “Special Github” extras like an admin section for adding/editing/deleting banned IPs! I also “cheated” by stealing elements from the Railscast on Rack Middleware.

The Ban Hammer

First off I generated a model called BannedIP by running script/generate model BannedIP ip:string and ran rake db:migrate to create the database and the banned_ips table.

After that, I made a file called lib/hammer.rb and it goes a little like:

class Hammer
  def initialize(app)
    @app = app
  end
  
  def call(env)
    if BannedIP.find_by_ip(env["REMOTE_ADDR"])
      file = "#{RAILS_ROOT}/public/banned.html"
      [403, {"Content-Type" => "text/html" }, [File.read(file)]]
    else
      @status, @headers, @response = @app.call(env)
      [@status, @headers, self]
    end
  end
  
  def each(&block)
    @response.each(&block)
  end
end

Eagle-eyes will see that this is almost a blatant rip-off of Ryan Bates’ code. Ignore that part. Admire that I call BannedIP.findbyip(env["REMOTE_ADDR"]) which will return an BannedIP object if one exists, otherwise it’ll return nil. in the case that someone’s banned then it’ll show them a very lightweight page with “You have been banned from this site.” and they’ll feel guilty and stuff (this feature actually coming in v2).

Now to use this middleware you have to add config.middleware.use ‘Hammer’ to your config/environment.rb file and (of course) restart the server. Every request will of course query the database once more which, if you’re running a large big HUGE site can lead to performance issues.

Of course you could just use iptables and do something like iptables -I INPUT -s 25.55.55.55 -j DROP, but then they won’t be told why they’re banned.

Construct

October 1st, 2009 by Radar

Over the past month or so I’ve learned to dislike Integrity for all it’s quirks. Whilst it’s a fabulous piece of software in theory the bugs (”notifyofbuild” fails, attempting to press “rebuild” attempts to go to a page that doesn’t exist, etc.) and it’s single threadedness has driven myself (and others) up the wall.

Last Tuesday I was in The Zone, and coded Construct effectively that night. It was as functional as integrity and didn’t hang when there was a build in progress! It works by running on port 80 and uses Github’s & Codebase’s post-receive hooks (you’ll have to set them up yourself I’m afraid).

So go try it out for yourself! Interested in your feedback for it.

Driver: Now In All New “Linux” Flavour

September 3rd, 2009 by Radar

That’s right, Driver (everyone’s favourite Passenger setup tool) is now able to run on Linux! I’ve only thus far tested it on Ubuntu, but there’s nothing foreseeable that would stop this running on any other distro. Let me know!

Driver

August 30th, 2009 by Radar

Over the past 24 hours I’ve worked (not constantly, in bursts) on a little Sinatra app called Driver. My inspiration for this was that Passenger Preference Pane was hanging in Mac OS X. Driver acts as an alternative to Passenger Preference Pane and it was a fun little project I did to see if it was possible, and it is. Now your challenge is to get it to work with Linux. Go for it!

Snow Leopard Ruby/Rails Developer Setup

August 28th, 2009 by Radar

If you don’t want to do a complete fresh re-install like I did, Jonathan Dance covers how to get things like the MySQL gem working again.

When I received my Snow Leopard disk I did a fresh re-install as I felt my computer was full of cruft and it was time to take out the trash. Of course, this meant also taking out all the cool apps / utilities etc that I use on a day-to-day basis. So here’s the stuff I’ve installed on my development box since I started.

Snow Leopard

Self-explanatory.

From the disk

Whilst you still have the disk handy (and by that I mean in the drive), it’d be wise of you to install from “Optional Installs” the “XCode” package. This provides gcc and other goodies, such as XCode (whodathunkit?). gcc will come in handy later on.

Utilities

MacPorts

I installed this from source and then installed curl with it. Apparently all the “important” packages are available and compatible, but you may find an edge case. Curl installed fine with this.

curl

Useful for retrieving websites or that odd XML feed from a provider. Installed via sudo port install curl

Git

To install Git I used the git-osx-installer, specifically the 1.6.4.1 version.

MySQL

Installing MySQL from package didn’t work for me (I don’t remember the error, or even if it was with the package or the gem, but it was a showstopper) so it was suggested via Google that I compile it from source. That I did and it worked out fine for me.

Other people have suggested to install the Mac OS X 10.5 (x86_64) version and to install the mysql gem using sudo env ARCHFLAGS="-arch x86_64" gem install mysql -- -with-mysql-config=/usr/local/mysql/bin/mysql_config.

PostgreSQL

Installed from source, the package complains that I do not have an appropriate version of Mac OS X installed. I tend to disagree. Installing the gem is possible, again suggested via Google and then promptly ignored and then brought up on Twitter.

Sphinx

When you go about installing this you probably want to configure it with BOTH MySQL support and PostgreSQL support. Just specify the --with-mysql and --with-pgsql options to ./configure.

Teleport

Teleport is an awesome app that allows you to send the keyboard and mouse from one computer to another to control it. Really awesome for when you’re pairing because you can both connect to one machine and then if you need to go off and do something independently the other person can continue working whilst you do that. To change screens move the mouse to the edge and keep it moving like you’re using dual-displays. Then you’ll have a teleport icon appear in the middle identifying what computer you’re on.

Caffeine

Caffeine will keep your Mac wide-awake whilst it’s switched on. Helpful for presentations where you’re talking for a long period of time and the screen dims.

smcFanControl

Do you live in a climate where dropbears run rampant and temperatures below 35 celcius (in summer) are classed as “cold” days? Then you’ll need SMC Fan Control. This little app speeds up your fans so your laptop can keep cool so you can too!

Rip

Rip is another package manager (think RubyGems done right) and some Ruby apps I’ve used (such as Integrity) use it for installing their packages.

Applications

Firefox

Firefox is now the most widely used browser in the world, so it’s just about mandatory that as a web user you have this installed. Of course along with Firefox you’re going to want to install Firebug too. Firebug gives you a window to inspect your HTML in, a console to test Javascript and a lot more; very, very powerful.

Tweetie

Tweetie is essential Mac-based twittering. Very hot and very intuitive (by that I mean Cmd+1 = public, Cmd+2 = mentions, etc.).

LaunchBar

A paid app, but well worth the money. This provides a box that you can type app / file / whatever names (partial + full) into and it’ll find them. Default shortcut is Command+Space and this is probably the app I cannot live without.

TextMate

If you’re developing Ruby on Rails on Mac you’ll need this, or an eidetic memory for all those vim shortcuts.

Limechat

RubyCocoa IRC Client.

Mailplane

Application for Gmail, I find it much better than the standard Mail app as it supports all of Gmail’s features (it’s effectively a wrapper for Gmail), costs money but worth it.

Skype

VoIP chatting thingo. Helpful for chatting with clients / faraway colleagues. You may want to go into Preferences -> Advanced and uncheck “Enable Mood Messages”, as this always makes Skype appear like it’s got a message when all that’s happened is someone’s changed the status.

Adium

Instant Messaging program, supports many different protocols.

Skitch

Screenshot + Annotation, one of my favourite apps on any platform.

AquaPath

Helpful little tool for testing out your XPath expressions.

Remote Desktop Connection

A surprisingly good piece of software from Microsoft. For those of you familiar with Windows XP and so on you may know of Remote Desktop Connection. This allows you to control another Windows computer, but in this case a Windows computer from a Mac.

TextMate Bundles

Cucumber

I mainly have this one for the syntax highlighting, but the shortcuts are good also.

Javascript Tools

Used mainly for syntax checking of Javascript, but has other tools like JSLint and compressng.

Ruby on Rails

drnic’s updated Ruby on Rails TextMate bundle. Contains all your favourite useful shortcuts.

Ruby HAML

Used for its syntax highlighting capabilities.

RubyAMP

Used to jump to class / method definitions throughout applications, contains other features too.

Gem Stuff

First of all you’re going to want to run gem update --system to get the latest and greatest RubyGems and then just about immediately after that you’re going to want gem source -a http://gems.github.com. If you’re upgrading rather than doing a fresh install it’s recommended by wycats to run gem pristine --all to recompile all natives.

Then you’re going to want to install:

  • rails
  • cucumber
  • mysql
  • sqlite3-ruby
  • rspec
  • rspec-rails
  • haml
  • chronic
  • launchy
  • thoughtbot-shoulda
  • thoughtbot-paperclip
  • mislav-willpaginate
  • mocha
  • passenger
  • sinatra
  • sequel
  • findgem
  • nokogiri
  • faker
  • fakeweb
  • notahat-machinist
  • mongrel
  • fastercsv
  • justinfrench-formtastic
  • adamcooke-codebase
  • capistrano
  • deprec
  • capistrano-ext and;
  • webrat
By using: sudo gem install rails cucumber mysql sqlite3-ruby rspec rspec-rails haml chronic launchy thoughtbot-shoulda thoughtbot-paperclip mislav-will_paginate mocha passenger sinatra sequel find_gem nokogiri faker fakeweb notahat-machinist mongrel fastercsv justinfrench-formtastic adamcooke-codebase capistrano deprec capistrano-ext webrat.

There are probably more gems I should install, feel free to specify these in the comments.

Dot Files

Some people have created repositories on github for their “dot files”, you know, .bashrc, .inputrc, .gitconfig and so on, the ones living in the home folder. I’ve done that too and you can find mine on Github too but be wary that rake install will overwrite your existing ones.

Misc

This is the stuff I can’t think to fit anywhere else:
  • Change your terminal to the Pro theme (because it is pro)
  • Anti-alias the terminal font
  • Change the hostname of your box (to something short and snappy)
  • Mac out the key repeat delay in Keyboard preferences
  • Change the “delay until repeat” option to be shorter, but not all the way
  • Keeping in Keyboard preferences, second tab, turn on all control tabbing.
  • Change the Dock minimisation effect:  -> Dock -> Dock Preferences -> Minimize windows using: “Scale effect”
  • Security preferences, ask for password on resuming from sleep / screen saver
  • Change TextMate to have soft tabs
  • Turn off terminal audible (and visual, but I don’t think this is enabled by default) bell
  • Turn off Front Row shortcut
If you can think of anything I’ve missed, please do not hesitate to leave a comment.

Octopi

August 26th, 2009 by Radar

There’s a couple of Ruby libraries out there for interacting with Github’s API but one caught my attention through recommendation through IRC channels, and that was Octopi by fcoury. Octopi covers just about everything the Github API has to offer and I was going to use it for a Rails Rumble project so I did some work on it, but pulled out from the competition due to flu & other commitments. In the past couple of days, I nagged fcoury about closing some of the issues on the project and he’s made me a collaborator on the project so I could do it, as his time is filled with Webbynode (they are awesome, check them out) stuff instead.

So I guess I all I have to say is: Go use the Octopi library for your Github stuff. It’s awesome.

distance_of_time_in_words

August 7th, 2009 by Radar

I was infatuated with this method when I first saw Rails but I’ve seen a couple of people recently express that Rails’ built in distanceoftimeinwords is not accurate enough, showing something like “about 2 years” rather than “2 years, 21 days, 5 hours, and 6 minutes”. With some help from chendo at Mocra (where I work) I’ve made a new distanceoftimeinwords which should be a drop-in replacement for the old crappy one. To install it, use: script/plugin install git://github.com/radar/dotiw.git. This also comes with another method if you’re still picky about the output: distanceoftimeinwords_hash which gives you a Hash containing keys in your native tongue. The README should give you a good guide of what other options it supports too.