Deploying Wordpress on Heroku

June 28th, 2012 by Sean Behan

Heroku unofficially supports PHP. Which means you can deploy Wordpress and get free blog hosting :)

Heroku runs


  • Apache version 2.2.22

  • PHP version 5.3.10

Deploying Wordpress to Heroku requires that you throw the Wordpress source into a Git repository. So download the latest stable build
and commit it.

wget http://wordpress.org/latest.zip
unzip latest.zip
cd wordpress
git init
git add .
git commit -m'init'

If you already have Heroku’s command line tool installed, great! If not you can download their toolset from here https://toolbelt.heroku.com/

Once installed, initailize an application on the Heroku platform.

heroku create --stack cedar

Wordpress (as far as I know) doesn’t support Postgres, which is the default database on Heroku. However, MySQL is
available as a free addon (5MB of space).

The plugin is called cleardb http://www.cleardb.com/. Cleardb is a MySQL-as-a-service company. You’ll have to tell Heroku that you want to use it.

heroku addons:add cleardb

**You may have to have a verified account to do this, which means you need to enter your credit card number under your account settings. I can’t remember
if this addon requires it. But so long as you stay on the cleardb free plan you won’t be charged.

Wordpress has a great self install tool, but we’re going to skip that. We need the config checked into Git so we don’t want Wordpress to do it for us on the deployed site. We can do it locally and check it in.
Rename the wp-config-sample.php to wp-config.php.

mv wp-config-sample.php wp-config.php

Replace the placeholder database configuration credentials with the connection details Heroku and Cleardb provide. To get this information run

heroku config

This will return the cleardb database connection url, which looks something like

CLEARDB_DATABASE_URL => mysql://[username]:[password]@[host]/[database name]?reconnect=true

Extract those credentials and plug them into wp-config.php where it says

/** The name of the database for WordPress */
define('DB_NAME', 'database_name_here');

/** MySQL database username */
define('DB_USER', 'username_here');

/** MySQL database password */
define('DB_PASSWORD', 'password_here');

/** MySQL hostname */
define('DB_HOST', 'localhost');

Commit the changes and deploy!

git add . 
git commit -m'database details'
git push heroku master

When you visit the site, Wordpress will walk you through titling and adding an admin username and password. To get the URL of the site run

heroku info

By default cleardb let’s you connect from anywhere. So if you’re running your local instance of Wordpress out of
a web enabled directory (Mamp, Wamp, ~/Sites etc.) your content will be production data.

Now you can edit your theme or edit plugins and deploy by pushing the branch to Heroku!

git push heroku master

You can also push other branches (not yet merged with master)

git push heroku other_branch:master

For more information about Heroku visit their dev center https://devcenter.heroku.com/

A Few Other Things To Think About

Heroku doesn’t have an MTA (Mail Transfer Agent) so your blog won’t be sending any email. There are a number of plugins for Wordpress that
let you configure SMTP, such as http://wordpress.org/extend/plugins/wp-mail-smtp/, if you need it.

To get nice URLS/Permalinks you should work on them in development and check in the auto generated .htaccess file. Because Heroku deploys to Amazon’s EC2, you’re not
guaranteed the same instance (filesystem) when you redeploy or restart the application.

heroku restart

And for the same reason above (you shouldn’t write to the filesystem) you will have to host assets not bundled with the source code elsewhere, for instance on Amazon S3. There
are quite a few plugins available, like http://wordpress.org/extend/plugins/tantan-s3/. Theme assets are fine, just assets that you would upload to attach to a blog post.

The Best Video About How to Make Money Online

June 25th, 2012 by Sean Behan

This is one of my favorite videos on the internet.

It is what got me interested in Rails and made me work toward the goal of running my own business and hopefully soon, launch my own products.

<iframe widtth=500 src=“http://www.youtube.com/embed/0CDXJ6bMkMY” frameborder=“0” allowfullscreen>

Installing Ruby with RVM without Xcode using CLANG

June 24th, 2012 by Sean Behan

I am not using the full Xcode package on my laptop. Instead I’m using the command line tools, offered by Apple as a separate and much smaller install. I haven’t had too many issues, aside from not being able to use the FileMerge program that ships with Xcode. I never thought I’d miss it. But compared to other merge tools out there, FileMerge rules.

Anyway, a frequent issue I run into is when installing Ruby with RVM, it complains with

The provided compiler '/usr/bin/gcc' is LLVM based, it is not yet fully supported by ruby and gems, please read `rvm requirements`.

The solution (which I found on this Stack Overflow Thread) is to tell RVM which compiler to use.

 rvm install 1.9.3 --with-gcc=clang 
 rvm install 1.8.7 --with-gcc=clang
 ...

You may still receive a notice things may not work as expected, but I haven’t run into anything yet.

How To Export A MySQL Database to JSON, CSV and XML with Ruby and the ActiveRecord Gem

June 23rd, 2012 by Sean Behan

It’s trivial to export data from a mysql database with Ruby and ActiveRecord. All you have to do is establish a connection and define a class that represents the table.

You can also use Bundler and a Gemfile to install dependencies. It might look something like this

You can install the dependencies by cding into the directory with the Gemfile and execute

bundle install

Bundler is a RubyGem so you will have to have it installed first.

gem install bundler

There is also a cool Gem callsed mysql2xxxx available at https://github.com/seamusabshere/mysql2xxxx

The Gem will let you run arbitrary sql statements and export them in either CSV, JSON or XML.

Here are some ways to use mysql2xxxx

mysql2csv --user=dbuser --password=dbpassword --database=dbname --execute="select * from automobile_makes"
mysql2json --user=dbuser --password=dbpassword --database=dbname --execute="select * from automobile_makes"
mysql2xml --user=dbuser --password=dbpassword --database=dbname --execute="select * from automobile_makes"

And to install

gem install mysql2xxxx

How To Add A Route With A Forward Slash in Params with Rails 3 Application

June 22nd, 2012 by Sean Behan

Use an asterisk in the pattern to match for everything after it. In the example below, date will be available in the params hash as params[:date].

SPB::Application.routes.draw do
  # http://example.com/calendar/2007/10 
  # params[:date] => "2007/10"
  match '/calendar/*date' => 'events#index', as: 'month'
end

How to Add Additional Sub Directories to the Default Rails Test:Unit File Structure

January 18th, 2012 by Sean Behan

How to Create a Date Time Snippet in Sublime Text 2 (Dynamic Signature with Time Stamp)

January 13th, 2012 by Sean Behan

You’ll have to create a new plugin. From the menu bar select

Tools > New Plugin

Copy the Python script from the signature.py file. Remember to replace your email address (it’s example.com).
Save the file, signature.py, is fine. Next open up Preferences > Key Bindings – Default and add a new entry.

ctl+alt+s will add the snippet to the first line of your file.

Transform Matching Text with Gsub in Ruby and Regular Expression

January 10th, 2012 by Sean Behan

Here is a gist that demonstrates how easy it is to transform text using #gsub and a block with Ruby.

For more helpful string extensions in Ruby check out our Ruby Gem on GitHub https://github.com/AgilionApps/rails_extensions

Color Output with Test:Unit, AutoTest and Ruby 1.9

January 8th, 2012 by Sean Behan

If you are testing using Test:Unit (rather than RSpec) and you’re using Ruby 1.9.* colorized output of your tests using Autotest will not be immediately available. Since, 1.9 comes with mini test the test/unit/ui/console/testrunner.rb script is not loaded and not available and will break your tests.

The solution is to require Test:Unit version 2.0.0 in your Gemfile, require the testrunner.rb script in test/test_helper.rb and reopen and implement the guess_color_availability method.

Then you can just run the autotest command (or bundle exec autotest) from your project directory. When you save a file your tests will be run for the file that has been changed and the results will be fully colorized!

How to Merge a YAML File Into a Single Hash in Ruby

January 8th, 2012 by Sean Behan

Class

September 23rd, 2011 by Sean Behan

# Define a class with a class method "find"
# Usage
# Apple.find("macintosh")
class Apple
   def self.find(variety)
      # code goes here
   end
end


# Same as above but notice the lack of self prefix before the method name
# Usage
# Apple.find("macintosh")
class Apple
   class << self
      def find(variety)
         # code goes here
      end
   end
end

See the full pastie here: http://pastie.org/2580020

Changing GitHub Issue State in Git Commit Message

July 7th, 2011 by Sean Behan

Changing issue state in git commit message for Github issues

fixes #xxx
fixed #xxx
fix #xxx
closes #xxx
close #xxx
closed #xxx

Example

git commit -am'complete bug fix closes #123'

Email Regex

July 3rd, 2011 by Sean Behan

Regular Expression that Matches Email Addresses:

/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b/

Vim Tips and Tricks

June 27th, 2011 by Sean Behan

The following tips and tricks can be put into your .vimrc file

Remap jj to esc

imap jj <Esc>

Quickly leave edit mode and back to visual mode with jj. This is probably the fastest key combination possible and one of the most frequent key combinations while editing in vim.

Remap semicolon “;”

nnoremap ; :

Instead of shift, semicolon (which produces a colon) just remap the semicolon to a colon while in visual mode.

You can alias commands with vim

command Tab, :tabnew

The only caveat is that your alias must start with a capital letter.

How to Upgrade RVM on Mac OS X

June 26th, 2011 by Sean Behan

I had an old version of rvm installed and wanted to upgrade. So old in fact that the resource for upgrading no longer existed.


rvm update

just returned a 301, redirect.

Luckily, the following worked

  1. checks out from repo
    rvm update —head
  2. will reload rvm environment
    rvm reload
  3. finally, the upgrade command works!
    rvm get latest

Ruby Reload! Method in Non Rails IRB Sessions

June 25th, 2011 by Sean Behan

I love the Rails reload! function when in the console. I need it in Irb. To get it back this is what I did. If you don’t already have an .irbrc file in your home directory, just create it.


vim ~/.irbrc
or textmate if you prefer
mate ~/.irbrc

Add this little snippet to it…


unless defined?(reload!)
$files = []
def load!(file)
$files << file
load file
end
def reload!
$files.each { |f| load f }
end
end

Usage : To load files in irb just use the method we defined in the .irbrc file “load!” notice the bang “!”. I don’t want to overwrite the actual load method. This load! method will just put the file in an array before loading it, so when running reload! it will iterate over this collection and load them again with whatever changes have since taken place. The unless conditional is so that you don’t overwrite the reload! method if you’re actually in the rails console.

How to Recover a Mistakenly Deleted Branch

June 21st, 2011 by Sean Behan

Workflow
git checkout -b _new_branch_name

  1. do some work and commit changed
    git checkout master
    git branch -d _new_branch_name
  2. doh… i meant to merge first

Fortunately, you can easily recover from this mistake.


git reflog
395b1ea HEAD@{0}: checkout: moving from _master_cleanup_akismet to master_cleanup
bd7df04 HEAD@{1}: commit: spam handling using akismet for form submissions on contact
submission and applicant models
395b1ea HEAD@{2}: checkout: moving from _master_cleanup to _master_cleanup_akismet
395b1ea HEAD@{3}: commit: cleaning up and adding some basic features
a828ef3 HEAD@{4}: checkout: moving from master to _master_cleanup

Should show you a list of commits across all branches in desc chronological order.

To merge the branch you just deleted you can give merge the sha.


git merge bd7df04

Which would match the commit at HEAD@{1}

Aliasing Attributes in Ruby on Rails

June 21st, 2011 by Sean Behan

Alias an attribute with alias_attribute method.

The first argument is the name for the new attribute, while the second argument is to identify the attribute that is already defined.

class User < ActiveRecord::Base
  alias_attribute :username, :login
end

Rails 3 Config Auto Load Paths in Application.rb

June 21st, 2011 by Sean Behan

In Rails 3 files in lib/ are no longer loaded by default. It’s a snap to auto load these classes by adding the following line to config/application.rb

    config.autoload_paths += %W(#{config.root}/lib)

This is commented out around line 16. Either replace it or uncomment it out to reflect the location where your lib classes are located.

How To Get A List of All Registered Mime Types in Rails

June 21st, 2011 by Sean Behan

When mime types are registered they are placed in a hash constant EXTENSION_LOOKUP in the module Mime. For reference, the file with the relevant code is in rails/action_pack/lib/action_dispatch/http/mime_type.rb available on Github at https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/http/mime_type.rb

You can check for existence of certain mime types with

Mime::Type.lookup_by_extension(:json)
which will return the object or nil if it’s not registered.
You can also iterate over all registered mime types by cycling through the constant like so
Mime::EXTENSION_LOOKUP.each { |m| puts m}

Api documentation is here: http://api.rubyonrails.org/classes/Mime/Type.html#method-c-lookup_by_extension

Git Feature Branch Naming Strategy

June 20th, 2011 by Sean Behan
There are only two hard things in Computer Science: cache invalidation and naming things.
— Phil Karlton

Typically, we have three main branches at any given time in a project lifecycle.

master, development and staging.

Master is production ready code, development is actively being worked on and staging is pre-flight testing before deploying master.

Features are branched off of development and use underscores to indicate distance from originating branch. For instance


_development_users
__development_users_reset_password

indicates that __development_users_reset_password branched off of development_users branch.
__development_users_reset_password_experiment
(3 underscores away) would indicate that I was experimenting with a branch off of development users reset password branch.

This provides a nice visual hierarchy when running git branch from the command line. It’s also helpful when you have multiple features being worked on by several people and you want to know where these branches are in relation to each other without needing to ask anyone. Here is a more complex example that illustrates the usefulness in using underscores in naming feature branches


__development_people_importing_csv

  • __development_people_importing_xml
    __development_users_password_reset
    _development_people_importing
    _development_users
    development
    master
    staging

My First Ruby Gem: Hashed_Attributes

June 20th, 2011 by Sean Behan

I just wrote and released my first Ruby Gem, Hashed Attributes https://rubygems.org/gems/hashed_attributes. It is a very simple ActiveRecord extension for saving variables through a serialized hash. The Gem will let you declare getter and setter methods that use a hash to store assigned data. For instance, instead of doing something like

user.preferences[:favorite_color] = 'orange'</pre>
you can do<pre>user.favorite_color = ‘orange’

The value for favorite color will be kept in a serialized hash.
<pre language=“ruby” line=“1>
person = Person.new(:favorite_color=>”orange")
{
:id => nil,
:preferences => {
:favorite_color => “orange”,
},
:created_at => nil,
:updated_at => nil
}

Setup in the model is very straight forward. The first argument is the column name you want to use followed by a list of methods used as keys on the hash.

  1. Example model
    class Person < ActiveRecord::Base
    hashed_attributes :preferences, :favorite_color, :theme, :plan # etc…
    end

ActiveRecord is required to use this gem. Additionally, you need to add a column in your database.

  1. Sample migration
    create_table :people do |t|
    t.text :preferences
    end

To install


gem install hashed_attributes

Or place in your Rails Gemfile

gem ‘hashed_attributes’

The project code is hosted on Github: https://github.com/bseanvt/hashed_attributes and https://rubygems.org/gems/hashed_attributes

Releasing this gem was a lot of fun and I’m looking forward to writing more gems!

Rails Send_File in Production Delivers an Empty File

June 14th, 2011 by Sean Behan

If you’re running Rails in production it will by default be configured to let apache or nginx send files for you. If you’re handling file downloads yourself with send_file


send_file(“path/to/file.txt”)

you will notice that the downloaded files are empty. To get around this just comment out the following in your config/environments/production.rb file.

  1. comment out for production because apache/nginx are not doing this for us
    #config.action_dispatch.x_sendfile_header = “X-Sendfile”

Git Untrack Already Tracked Files

June 14th, 2011 by Sean Behan

To remove files that are currently being tracked by git, you have to remove them from the “cache”. Note, doing this will NOT delete the file on your local machine. It will still be there but not be tracked.

 git rm -r —cached supersecretpasswords.txt 

You then need to add the file to the .gitignore file in the root of the project so that it isn’t tracked again on your next commit.

vim .gitignore
supersecretpasswords.txt


.gitignore files are tracked so remember to check in these changes.

git commit -am’my super secret passwords are safe!’

If you want to completely delete the file, on your local machine and from git


git rm supersecretpasswords.txt

If you’re working with a directory remember to add the -r flag for recursive removal!

Rails Find All by Birthday: How to Find Upcoming Birthdays with ActiveRecord

June 12th, 2011 by Sean Behan

There are a few ways to solve this problem. However, I think the easiest is to cache the day of the year that the user is born on as an integer. If stored alongside the timestamp we can quickly get a list but properly handle the full birthday elsewhere, such as in the view. You don’t want to rely on just the cached day of year because leap year is not accounted for.

The model will need both born_at and birthday columns.


create_table :users do |t|
t.timestamp :born_at # full timestamp
t.integer :birthday # just the day of year
end

The user model also needs a callback (before_save) to set and or update the cached birthday column based on the full timestamp. For convenience, a named scope can be added to the model which will let you call User.birthdays.


class User

  1. User.birthdays
    scope :birthdays, lambda { where(‘birthday in(?)’, 7.times.map{|i| Time.now.yday + i}) }
def before_save self.birthday = born_at.yday end

end

You could also use the week in year (1 – 52) for the cache. Using the day you can look an arbitrary number of days ahead.

Git: How to Delete a Branch with an Invalid Name

June 5th, 2011 by Sean Behan

If you’ve named a branch beginning with two dashes “—”, you’re sort of in trouble because git interprets your branch name as a switch/flag. You can skip switches all together
by supplying two dashes before your branch name

git branch -d -- --index_for_suppliers

and your branch will be deleted!

How to Remove Your Last Git Commit

June 5th, 2011 by Sean Behan

Remove your last commit (if you haven’t pushed yet)

git reset --hard HEAD~1

To see changes that have been committed and their position in HEAD

git reflog 

And to undo your previous reset and advance the cursor to the reference immediately behind the current state

git reset —hard HEAD@{1}

If you have already pushed you can

git revert HEAD

which will reverse your last commit by creating a new commit

Backup and Rotate MySQL Databases Simple Bash Script

June 4th, 2011 by Sean Behan

Make a directory ( it can anywhere ) called baks/mysql


mkdir -p /baks/mysql

Create a file (it can be anywhere) called /root/mysql_backups.sh and put this script in it


#!/bin/bash

  1. modify the following to suit your environment
    export DB_BACKUP=“/baks/mysql”
    export DB_USER=“root”
    export DB_PASSWD=“your-mysql-password-goes-here”
  1. title and version
    echo ""
    echo “Backup and rotate all mysql databases”
    echo “-———————————-”

rm -rf $DB_BACKUP/04
mv $DB_BACKUP/03 $DB_BACKUP/04
mv $DB_BACKUP/02 $DB_BACKUP/03
mv $DB_BACKUP/01 $DB_BACKUP/02
mkdir $DB_BACKUP/01

echo “* Creating backup…”
mysqldump -user=$DB_USER —password=$DB_PASSWD —all-databases | bzip2 > $DB_BACKUP/01/mysql`date +%Y-%m-%d`.bz2
echo “-—————————-”
echo “Done”
exit 0

Install it via cron and have it run at 3:10 am every morning.


crontab -e

10 3 * * * /root/mysql_backups.sh > /baks/status.log

This script will save the last 4 days of data.

Ruby Rand Range

June 4th, 2011 by Sean Behan

I assumed that rand would take a range as an argument. Something like rand(10..20), generating a random number between 10 and 20. Seems like you’d do this fairly often when working with random numbers and therefore, included. However, it doesn’t work. But the solution is almost as easy.

10 + rand(11) #=> produces a random number between 10 and 20

Since rand starts at 0 (like array indexes), we need to add an extra 1 to get what we’re expecting.

Free Online Design Tools and Resources for Programmers

June 1st, 2011 by Sean Behan

I’m a programmer. At least I want to be. But the reality of web development requires wearing multiple hats. This includes from time to time, working on design. After all what is a web app if it is poorly designed? Both UI and aesthetics are important from customer/user perspective.

Fortunately, there are many great designers who are also developers (or who have developer friends) and they release cool tools to help out. So here is a list of resources I’ve found useful when wearing the designer hat.

http://0to255.com/ – when working with color
http://framebox.org/ – rapid prototyping and sharing

http://subtlepatterns.com/ – spice up the background with some subtle patterns

http://www.html-ipsum.com/ – lorem ipsum text wrapped in different html elements

http://placehold.it/ – placeholder image spaces
http://flickholdr.com/ – placeholder images from flickr
http://placekitten.com/ – turns any project into a success

http://www.copypastecharacter.com/ – copy and paste special characters/lookup
http://www.cssbuttongenerator.com/ – make nice css buttons
http://www.colorzilla.com/gradient-editor/ – css gradients
http://www.red-root.com/sandbox/holmes/ – clean up, css debugger
http://gridulator.com/ - make a grid layout

http://warpspire.com/talks/designhacks/ Not necessarily a tool, but a great presentation on design geared at developers

Link to jQuery Source from Google's CDN

May 28th, 2011 by Sean Behan

https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js

That is the link to the jQuery source hosted by Google on their CDN. It’s probably already cached on client machines so it should be as fast as is possible! You can read more/use other Javascript libs from Google’s CDN here: http://code.google.com/apis/libraries/devguide.html#jquery

Simple String Concatenation of a Collection Written as a Helper for Rails

May 24th, 2011 by Sean Behan

At Railsconf last week I took Greg Pollack’s online course Rails Best Practices. The interface is gorgeous and the instructions are excellent. One of the lessons involved taking a partial and moving it into a helper. I was reminded how difficult such a simple task can be. I have written about this before Yield a Block Within Rails Helper Method with Multiple Content Tags. However, that post aims to solve a slightly different problem, where the helper method takes the captured text from a block passed as an argument which essentially acts as a wrapper.

The difficulty isn’t with the logic itself and or the complexity/verbosity that the code is likely to produce. Rather, it is difficult because you have to endlessly concatenate strings and this something somewhat uncommon when programming with ruby. We have to remember that we’re working with a buffer of text about to be flushed. Here is a simple code snippet that shows how to write a helper method that loops over a collection of objects.

  def bookmarks_for(user=nil)
    content_tag(:div, :id => "bookmarks") do
      user.bookmarks.each do |bookmark|
        concat(
          content_tag(:strong) { bookmark.member_name } +
          excerpt(bookmark.body, '', 100)
        )
      end.join
    end
  end

Notice the use of the concat() method the “+” sugb and .join() method. All three of which bring these statements together into one final piece of html called in the view.


<%= bookmarks_for(@user) %>

How to Copy and Paste to/from the Global Register with Tmux on Mac OS X

May 14th, 2011 by Sean Behan

Using the system clipboard with tmux on OS X is broken. I really like tmux but having copy and paste is kind of important for me. Here is my attempt to get it back with a simple bash script until I find something better. The approach is to take a named pipe and feed it the contents of “tmux showb”. A bash script will manage the pipe and because this script is initialized from a normal session it will write to the system clipboard just fine.

In my .bash_profile…


pipe4tmux=/tmp/pipe4tmux
alias tcp=“tmux showb > $pipe4tmux”
if [[ ! -p $pipe4tmux ]]; then
~/pipe4tmux.sh &
fi

And in pipe4tmux.sh…


#!/bin/bash
pipe4tmux=/tmp/pipe4tmux
echo “Starting named pipe $pipe4tmux”
trap “rm -f $pipe4tmux” EXIT

if [[ ! -p $pipe4tmux ]]; then
mkfifo $pipe4tmux
fi

while true
do
pbcopy < $pipe4tmux
done

echo “Quitting pipe4tmux $pip4tmux”

Reusing Scopes (Formerly Named_scope) In Rails 3

May 5th, 2011 by Sean Behan

You can easily chain scopes together in your models.
class Article < ActiveRecord::Base scope :ordered, order('position ASC') scope :published, ordered.where('published = ?', true) scope :for_homepage, published.limit(3) end

Article.for_homepage.to_sql

  1. => SELECT \“articles\”.* FROM \“articles\” WHERE (published = ‘t’) ORDER BY position LIMIT 3

Installing MatPlotLib on OS X for Python Version 2.6.1 with PIP and VirtualEnv

April 23rd, 2011 by Sean Behan

If you thought you had installed matplotlib only to find this
File "/Library/Python/2.6/site-packages/matplotlib-0.91.1-py2.6-macosx-10.6-universal.egg/matplotlib/numerix/__init__.py", line 166, in <module> __import__('ma', g, l) File "/Library/Python/2.6/site-packages/matplotlib-0.91.1-py2.6-macosx-10.6-universal.egg/matplotlib/numerix/ma/__init__.py", line 16, in <module> from numpy.core.ma import * ImportError: No module named ma
It is because the package being installed is version 0.91 and you need at least version 1.0 .

If it’s already installed pass pip the upgrade flag and specify the package location with the “-f” flag
pip install --upgrade -f http://downloads.sourceforge.net/project/matplotlib/matplotlib/matplotlib-1.0/matplotlib-1.0.0.tar.gz matplotlib

If not installed
pip install -f http://downloads.sourceforge.net/project/matplotlib/matplotlib/matplotlib-1.0/matplotlib-1.0.0.tar.gz matplotlib

Resources:
http://stackoverflow.com/questions/3555551/why-does-pip-install-matplotlib-version-0-91-1-when-pypi-shows-version-1-0-0

Installing Ruby on Rails 3, MySQL, Git, Ruby Enterprise Edition, Passenger (Mod_Rails) on Ubuntu with Rackspace Cloud.

March 23rd, 2011 by Sean Behan

Short and sweet. Here all the commands I run in this order to set up a brand new box. It usually takes about 10 – 15 minutes on a 256 MB RAM instance. Compiling Ruby Enterprise Edition, which is super easy, will take the most amount of time. It will seem to have gotten stuck. It hasn’t. It just takes a little while.

  1. Update, upgrade and install all necessary packages for Ruby on Rails server if you’ve got a fresh Ubuntu slice
    apt-get update
    apt-get upgrade

apt-get install build-essential patch libssl-dev libreadline5-dev

apt-get install ruby1.8-dev ruby1.8 ri1.8 rdoc1.8 irb1.8 libreadline-ruby1.8 libruby1.8 libopenssl-ruby imagemagick librmagick-ruby1.8 librmagick-ruby-doc libfreetype6-dev xml-core postfix

  1. postfix will prompt you for details
  2. use Internet Site and enter in the domain name you are planning on sending email from

apt-get install apache2 apache2-prefork-dev libapr1-dev libaprutil1-dev libcurl4-openssl-dev git-core mysql-server mysql-client libmysqlclient15-dev libmysql-ruby

  1. mysql will also prompt you to set up a root user account. set the password to be anything you like
  1. next, download the latest release of ruby enterprise edition but when you’re installing it on your own machine version numbers and release dates may have changed.
  2. pay attention to the version and release date before the file extension. it will be something like
  3. … 1.8.7-2010.02
  4. this will change to something like 2011.03, 2011.04… etc in the future.
  5. just double check the paths on when you are installing and make the necessary substitutions
  1. ruby enterprise edition is available at http://www.rubyenterpriseedition.com/download.html
    wget http://rubyforge.org/frs/download.php/71096/ruby-enterprise-1.8.7-2010.02.tar.gz
    tar xzvf ruby-enterprise-1.8.7-2010.02.tar.gz

./ruby-enterprise-1.8.7-2010.02/installer

  1. this may take a little while (just follow the instructions)
  2. and hit enter to install in default location (recommended) when prompted
  1. and to install passenger (which is mod_rails for apache)
    /opt/ruby-enterprise-1.8.7-2010.02/bin/passenger-install-apache2-module
  1. i take the output from the above script and add it to my available modules directory
    vim /etc/apache2/mods-available/passenger.conf
  1. and enter something like this in the newly created file (your version numbers will prob. be different)
    LoadModule passenger_module /opt/ruby-enterprise-1.8.7-2010.02/lib/ruby/gems/1.8/gems/passenger-3.0.2/ext/apache2/mod_passenger.so
    PassengerRoot /opt/ruby-enterprise-1.8.7-2010.02/lib/ruby/gems/1.8/gems/passenger-3.0.2
    PassengerRuby /opt/ruby-enterprise-1.8.7-2010.02/bin/ruby
  1. and then sym link it to the enabled directory so that apache knows about it
    ln -s /etc/apache2/mods-available/passenger.conf /etc/apache2/mods-enabled/passenger.conf
  1. and now i want to include ruby enterprise edition in my path so i add it to my profile (again make sure the path is correct)
    vim /etc/profile.d/passenger.sh
    export PATH=/opt/ruby-enterprise-1.8.7-2010.02/bin:$PATH

. /etc/profile.d/passenger.sh

  1. the “.” file will make the setting available for the current terminal session
    rails -v
    ruby -v
    rake -v
  2. should all be working now
  3. and
    which ruby
  4. should point to the ruby enterprise edition under /opt
  1. next i
  2. set up public/private keys
  3. so i can do
  4. ssh localhost without using a password
    cd
    test -e ~/.ssh/id_dsa.pub || ssh-keygen -t dsa
    cat ~/.ssh/id_dsa.pub >> ~/.ssh/authorized_keys2
  1. and finally install git
    apt-get install git-core

You should now have a server ready to server ruby on rails applications!

Rails 3 disable_with Does Not Work with Ajax Remote Form_for

March 15th, 2011 by Sean Behan

It appears that the :disable_with option on the submit_tag form helper method does not behave as expected with remote forms. I’m not sure if this is a bug or not. But the fix is pretty straight forward, but perhaps a little difficult to trouble shoot. Using submit_tag inside a remote form


<%= submit_tag “Submit”, :disable_with => “Submitting….” %>

Will not work.

You have to edit your public/javascripts/rails.js file around line #167

and change

document.on("ajax:after", "form", function(event, element) {

to

document.on("ajax:complete", "form", function(event, element) {

Then things will behave as expected. This assumes you are using Prototype (rather than jQuery).

Execute Javascript When Using Link_to_function To Include a Partial in Rails

October 2nd, 2010 by Sean Behan

If you use the link_to_function to replace content in a div with content from a partial, any javascript that you include in the partial will not be executed. It is instead included, but will do nothing. Obviously, this isn’t the desired behavior. Why would we be taking the trouble to write the javascript in the partial? There is an easy fix. Instead of writing out the script tags, instead use the javascript_tag  method to wrap whatever javascript you would like executed when the partial is loaded.

<%=link_to_function “say hello” {|p| p.replace_html “container”, :partial => “say_hello” }%>

And now in my say_hello.erb file
<% javascript_tag do >
  alert(“Hello World”);
<
end %>

Rails Select Tag and Onchange Event Calling a Remote Function with Default Option Selected

October 2nd, 2010 by Sean Behan

Here is a little code snippet that will fire off a request to update_client_path when you change the select field. This stands alone, rather than being apart of a larger form. The Client::CATEGORY argument is a hash, which I populated manually in my Client.rb model. It is something like this


CATEGORY = {:lead => “Prospective clients”, :past => “Previous clients…”}

In my view I have

<%= select_tag “client_category”,
options_for_select(Client::CATEGORY.keys, client.category.to_sym), { :onchange =&gt; remote_function( :url =&gt; update_client_path(client), :with=>“‘change_to=’this.value’’” ) } %>

One gotcha is that the select_tag, options_for_select argument expects a symbol if you’re passing in a hash as the type of the collection! It may not set the default if you provide it with a string for the second arg (which specifies which option should be set as selected).

You also need to make sure that the url update_client_path is set in your routes file and that your controller (clients_controller in this case) has the appropriate method to handle the request.

Ruby Enterprise Edition and Passenger ./script/console production fails and instead returns Loading production environment (Rails 2.3.5) Rails requires RubyGems >= 1.3.2. Please install RubyGems and try again: http://rubygems.rubyforge.org

October 1st, 2010 by Sean Behan

After installing Ruby Enterprise Edition, REE, and Passenger on Ubuntu you may see this error message when you run script/console for the first time


./script/console production

  1. =>
    Loading production environment (Rails 2.3.5)
    Rails requires RubyGems >= 1.3.2. Please install RubyGems and try again: http://rubygems.rubyforge.org

You then scratch your head and run

which gem
which ruby
which rails

to find that all appears to be in order. You have rubygems installed , ruby is installed and so is rails. You also find that each are pointing to the correct location, which is something like /usr/bin/gem → /opt/ruby-enterprise-x.×.×.x/bin/gem, where x.×.×.x is the version of REE.

The problem isn’t however, with any of the above. The issue is with the location of irb. If you installed (like me) irb with apt-get install irb, then irb isn’t aware of your shiny new REE and ruby gems. It’s a simple fix however, unlink irb and symlink the /usr/bin/irb to REE’s irb like so…


rm /usr/bin/irb

And symlink it to the irb that REE has in bin

ln -s /opt/ruby-enterprise-x.×.×.x/bin/irb /usr/bin/irb

Now cd into your rails app and run


./script/console production

How Many Gigs of RAM Are On My Server?

September 21st, 2010 by Sean Behan

How much memory is on my linux server? Run the free command


free -g
total used free shared buffers cached
Mem: 2 1 0 0 0 1
-/+ buffers/cache: 0 1
Swap: 3 0 3

Which will tell you memory in Gigs. You can pass other flags, such as, -m or -k, which will give you the number in megs and kilobytes respectively.

The man page is as follows


man free

FREE Linux User’s Manual FREE

NAME
free – Display amount of free and used memory in the system

SYNOPSIS
free [-b | -k | -m | -g] [-o] [-s delay ] [-t] [-V]

DESCRIPTION
free displays the total amount of free and used physical and swap memory in the system, as well as the buffers used by the kernel. The shared memory column should be
ignored; it is obsolete.

Options The -b switch displays the amount of memory in bytes; the -k switch (set by default) displays it in kilobytes; the -m switch displays it in megabytes; the -g switch displays it in gigabytes. The -t switch displays a line containing the totals. The -o switch disables the display of a “buffer adjusted” line. If the -o option is not specified, free subtracts buffer memory from the used memory and adds it to the free memory reported. The s switch activates continuous polling delay seconds apart. You may actually specify any floating point number for delay, usleep(3) is used for microsecond resolu tion delay times. The -V displays version information.

FILES
/proc/meminfo
memory information

SEE ALSO
ps(1), slabtop(1), vmstat(8), top(1)

Have Git Email Committers After Pushes

September 14th, 2010 by Sean Behan

You need a Mail Transfer Agent MTA on the server. The easiest way is to install Sendmail, which Git uses by default.


apt-get install sendmail

Remember that /etc/hosts file needs the ip address to map to the domain name your sending mail from

  1. vim /etc/hosts
    127.0.0.1 localhost localhost.localdomain
    207.136.202.87 wwwexample.com

Sendmail has a tendency to hang when sending mail otherwise. To test sendmail

sendmail email@example.com
this is a test
how are you today world?
.

The period on a line by itself denotes end of message and will terminate the prompt and deliver the message.

Now you need to configure Git to send email after it receives a “push” from a committer. You can add email addresses, or you can set up a mailing list to email all members. Either way, you accomplish this with the following command, just remember to cd into the git repository.


git config —add hooks.mailinglist “mailinglist@example.com”

Next you need to activate the post-receive hook, located in the hooks directory of your repository.

cp post-receive.sample post-receive

And uncomment the last line, which uses sendmail to deliver the commit message

  1. uncomment the last line but keep the period “.”
    . /usr/share/doc/git-core/contrib/hooks/post-receive-email

All done. Now just make some changes to your source code, add and commit them and you should receive an email with all the details!

Setting Up Users, Permissions and Groups for SSH Access to a Shared Git Repository

September 13th, 2010 by Sean Behan

If you are having permission problems using git, such as

error: insufficient permission for adding an object to repository database ./objects

There are a couple thing you can do to remedy the situation, before moving to a full on git server like gitosis.

Create your users and add them to a group. Create (if you haven’t already) your git repo on the server and change permission and ownship and set the git config sharedRepository to true.

Here are all the commands, quick and dirty!


adduser sean
adduser jackson
groupadd developers
adduser sean developers
adduser jackson developers

mkdir -p /git/dev/app.git
cd /git/dev/app.git
git —bare init
vim description #edit this file (mac os x complains otherwise)
chmod -R g+ws *
chgrp -R developers *
git repo-config core.sharedRepository true

Found from: http://mapopa.blogspot.com/2009/10/git-insufficient-permission-for-adding.html

Installing and Using Rvm on Mac OS X, Creating Gemsets and Reverting to Original Environment

September 13th, 2010 by Sean Behan

What is RVM and why should you use it? RVM is a Ruby interpreter, version management tool. In short, it enables you to switch between different versions and releases of Ruby (for instance, version 1.8.6, 1.8.7, jruby 1.9.2, ruby enterprise edition) on the same machine, while associating different gems with each version of the ruby interpreter. This is super useful and awesome. If you want to play with Rails 3 and Ruby 1.9.1, for 5 minutes, and then want to switch back to your production apps, which are running on Rails 2.3.5 and Ruby 1.8.7, you can do so with a single command from the terminal. With RVM this is a fairly simple process so there is no reason not to install it. You can also revert back to your system settings (not using RVM) with a single command. After all Rails is just a gem, so you can easily create and manage different RVM “gemsets”, (sets of different gems), for the different versions of Ruby (rubies as RVM refers to them) you have installed.

Installing RVM


bash < <(curl -s https://rvm.beginrescueend.com/install/rvm)

Next you have to add rvm to your bash profile

  1. place in ~/.bash_profile as the very last line
    [[ -s “$HOME/.rvm/scripts/rvm” ]] && . “$HOME/.rvm/scripts/rvm”

To check everything went well


type rvm | head -n1

Should tell you “rvm is a function”

How to add ruby, pass it the version to install


rvm install 1.8.7

*The current terminal session will load this environment. New sessions will not. To use a version of ruby and set it as the default, pass it the —default option

rvm use 1.8.7 —default

Next create a gemset, which will make available different gems for different versions


rvm gemset create rails_2_3_5

When you run “gem list”, you should see nothing!


gem install rails -v=2.3.5

Set a default rvm and default gemset, specify which gemset with the @ sign and include the —default option


rvm use 1.8.7@rails_2_3_5 —default

which gem
gem list 
ruby --version
rails --version 

And to get back to where you started and revert to using your original ruby setup


rvm system

For upgrading your version of RVM check out this post I wrote http://seanbehan.com/ruby/how-to-upgrade-rvm-on-mac-os-x/

Finally, you can create a .rvmrc file and put it in any directory and when you cd into that directory the environment specified in the file will be loaded automatically. This way you don’t have to remember the version and gemsets and type them into the console. All you have to do is put the ruby version and gemset name in the file like so

ruby1.8.7@rails2.3.5

You’ll be prompted to trust the .rvmrc file the first time, type “y” for yes. Also, subdirectories will inherit this .rvmrc so you can just put it in the parent directory like

rails2/
     .rvmrc
     app1
     app2
rails3/
     .rvmrc
     app1
     app2

And both app1 and app2 will use the .rvmrc environment while your rails3 directory apps will load the environment in its directory!

More information available here:
http://rvm.beginrescueend.com/rvm/install/
http://www.stjhimy.com/posts/4
http://eddorre.com/posts/installing-rails-3-beta-4-using-rvm

Renaming Routes in Rails 3 with :As and :Controller

September 13th, 2010 by Sean Behan

Renaming routes in Rails 2.* is straight forward. It goes something like this.

  1. config/routes.rb
    map.resources :users, :as => :members

This will give you users_path and form_for(User.new) helpers, for instance, mapping the url to /members instead of /users while using the users_controller.rb class.

In Rails 3.*, this is still possible. It is accomplished differently. In my opinion, it seems a little less elegant.

  1. config/routes.rb
    resources :members, :as => :users, :controller => :users
  2. app/views//.erb
    link_to “Members”, users_path
    form_for User.new do |f|
  3. Rake routes
    users GET /members(.:format) {:controller=>"users", :action=>"index"}
    users POST /members(.:format) {:controller=>"users", :action=>"create"}
    new_user GET /members/new(.:format) {:controller=>"users", :action=>"new"}
    edit_user GET /members/:id/edit(.:format) {:controller=>"users", :action=>"edit"}
    user GET /members/:id(.:format) {:controller=>"users", :action=>"show"}
    user PUT /members/:id(.:format) {:controller=>"users", :action=>"update"}
    user DELETE /members/:id(.:format) {:controller=>"users", :action=>"destroy"}

Your resource is “members” and you are overriding the name (using :as=>"users") however, you still have to specify the controller.

http://pastie.org/1154956

Combat Spam with the Akismet Class for Ruby

September 10th, 2010 by Sean Behan

Here is the Akismet.rb class, written by David Czarnecki. I’ve seen several tutorials online using this class, however, the class isn’t available at David’s blog. So… I reposted it here and at the pastie link below
http://pastie.org/1150693

Running Gem Server to View Docs for Ruby Libraries on Localhost

September 9th, 2010 by Sean Behan
gem server

will boot up documentation on port 8808 by default pass it the -p flag followed by the port number to change.


gem server -p3000

Uploading Files with Curl

September 8th, 2010 by Sean Behan
curl -i -F name=test -F filedata=@localfile.jpg http://example.org/upload

Courtesy of http://ariejan.net/2010/06/07/uploading-files-with-curl/

Using to_sentence method on an Array in Ruby on Rails

September 8th, 2010 by Sean Behan
Member.all.collect {|member| member.firstname}.to_sentence
=> "Alex, Andy, and Sean"

Declare separator and the connector


Member.all.collect {|member| member.firstname}.to_sentence(
:connector => “and last but not least,”,
:skip_last_comma => true
)
=> “Alex, Andy and last but not least, Sean”

Collection Select Helper and OnChange Event in Rails

August 31st, 2010 by Sean Behan

Given a collection of Active Record objects, you may use the collection_select helper method to produce a select form field. You need to pass in a number of arguments to the helper function.

1) object – your model object used in the collection
2) method – a valid model attribute or method
3) collection – a collection of active record model objects
4) option_value – value being set from the model for the <option value=“option_value”> html element
5) option_name – what is displayed for the user e.g., <option> option_name <
6) option – general options
7) options for the select html element

# helper and arguments…

  1. collection_select( model, id, collection, option_value, option_name, options, html_options)

<%= collection_select(“states”, “state_id”,
State.participating,
“abbreviation”, “name”,
{:selected=> get_current_state_or_nil },
{:onchange=>“document.location=‘/states/’+this.value”}
) %>

#which will produce something like…

&lt;select id="state_id" name="state[id]" onchange="document.location='/states/'+this.value"&gt;
&lt;option value="AL"&gt;Alabama&lt;/option&gt;
&lt;option value="AK"&gt;Alaska&lt;/option&gt;
&lt;option value="AZ"&gt;Arizona&lt;/option&gt;
&lt;option value="AR"&gt;Arkansas&lt;/option&gt;
&lt;/select&gt;

Repost

August 26th, 2010 by Sean Behan

This post is inspired by
http://pupeno.com/blog/really-resetting-the-database/#comment-1179
. But as my blog mostly serves as a reference for my future self, I’d like to reprint this little snippet of code here as well.

namespace :db do
  desc "Crush and burn the database"
  task :hard_reset => :environment do
    File.delete("db/schema.rb")
    Rake::Task["db:drop"].execute
    Rake::Task["db:create"].execute
    Rake::Task["db:migrate"].execute
    Rake::Task["db:seed"].execute
    if !Rails.env.test?
      Rake::Task["db:data"].execute
    end
  end

  desc "Generate sample data for developing"
  task :data => :environment do
    # Create the sample data in here
  end
end

Rounded Corners with CSS

August 26th, 2010 by Sean Behan
.rounded_corners {
     -moz-border-radius: 20px;
    -webkit-border-radius: 20px;
    -khtml-border-radius: 20px;
    border-radius: 20px;
}

Select Distinct in Rails with Active Record

August 25th, 2010 by Sean Behan
User.find :all, :select => "DISTINCT occupation"

A List of Every High School in the United States in Pipe Delimitted Form (2005)

August 25th, 2010 by Sean Behan

Here is a text file containing every high school in the United States(2005), including city, state, zip code and high school name.

us_high_schools_pd

The Context of Markup vs Expressions of Equality in Determining the Meaning of Angled Brackets

August 23rd, 2010 by Sean Behan

In the Wordpress editor (html mode) you’ll need to become friends with < and > if you plan on showing any code (php, html… xml, most languages actually) that readers will want to understand.

I never thought about it, but assumed that the lt and gt stood for left, and gt, well, i couldn’t quite place it, respectively. But alas, it dawned on me. Lt = less than while gt = greater than. Seems obvious now, but when you are thinking about angled brackets as markup, rather than as logic in an expression, the meaning that has value happens to be left vs. right.

Context is important.

Simple Activity Stream Implementation in Rails

August 23rd, 2010 by Sean Behan

There are many ways to tackle the Facebook style activity stream feature for your app. The simplest approach, which you can tack on at almost any moment, is what I’ll describe here. You don’t have to create a new model for news feed items or create any polymorphic associations. You simply query for the records on separate models you would like aggregated in the stream, and render a partial for that record, which Rails will map for you.

# in app/controllers/home_controller.rb
def index
 @activity_stream = (Forum.find(:all, :limit =&gt; 10, :conditions=&gt;["created_at &gt; ?", 1.day.ago]) + ForumPost.find(:all, :limit =&gt; 10)).sort_by {|item| - item.created_at.to_i}
end  

The sort_by method at the end places all of your feed item into descending chronological order. Omit the minus sign and they will be sorted in ascending order.

  
sort_by {|item| – item.created_at.to_i} # in descending chronological order

Show your latest activity in your views…


#app/views/home/index.html.erb
<%= render @activity_stream rescue nil %>

This assumes that you will have created the partials for each resource using Rails conventions i.e., you have in created the partials for the models like so app/views/[the model name].html.erb. In this instance, you should have app/views/forums/forum.html.erb and app/views/forum_posts/forumpost.html.erb

You can rename the partials to something like _stream_forum.html.erb, if you already have the forum partial gainfully employed. You’ll need to change the view and prob. throw it into a loop to either check for a condition or use stream[model name].html.erb as the convention for any stream items.

Scope Routes/URLs By Username (like Twitter) in Your Rails Application

August 22nd, 2010 by Sean Behan

There are a few things that need to be taken care of before you can get this to work. The first thing (although, any of the following steps can be done in any order) to take care of involves your User model. You need to override the to_param method, so that Rails will appropriately use the username attribute rather than user_id when constructing paths.

  
#in app/models/user.rb
def to_param
“#{self.username}”
end

Next we move onto routing our resources. Here it gets a little tricky because Rails is building paths for us. Remeber, you can get a list of all currently defined routes in your application by running the routes rake task


rake routes

We need to set the path_prefix option on any of our resources we want scoped by the username. For instance, in this example, I have set up a Status model and statuses_controller, whose urls shall be scoped by the username. You can apply the path_prefix to any number of other resources in your routes config file. They symbol used is arbitrary, but will be made available in the params hash, in this case params[:user_id]. You also need to exclude the show action on your users resources declaration. The reason is that, otherwise, Rails will include the controller name in the path like /users/username, which doesn’t look as clean as just /username. You then need to redefine this route explicitly (last line in the routes config shown here).

#in app/config/routes.rb
map.resources :statuses, :path_prefix => ‘/:user_id’
map.resources :users, :except => [:show]
map.user ‘/:username’ :controller => ‘users’, :action => ‘show’

Finally, you get to call these routes in your views or use them in your controllers. You use the same link_to, url_for methods to generate paths. When constructing the resources you have setup with the path_prefix declartion, remember you need the user model as the first argument, followed by said resource.

&lt;%= link_to(status.title, status_path(status.user,status) %&gt;
# or in a controller
redirect_to status_path( status.user, status )

That’s pretty much it. If anyone has another way of doing this let me know!

Using Formtastic to Cleanly Create Nice Looking Forms in Rails

August 22nd, 2010 by Sean Behan

Forms can easily get cluttered when you’re dealing with a lot of form fields… er, ERB tags. I’ve written about extending Rails form builders, which certainly goes along way to shrinking your views where forms are used. The plugin Formtastic is even better, as it lets you skirt maintaining your own library in favor of a very, elegant DSL.

For a great overview of the plugin and implementation details, check out Ryan Bate’s Railscast. There are a couple episodes, but be sure to catch the first one, linked above.

I usually install the plugin as a gem

# config/environment.rb
#…
config.gem “formtastic”

and then run a generator to create the stylesheets for me, making forms look nice and neat.
./script/generate formtastic

One gotcha, is that in order for the css to render correctly you need to add this
<html xmlns=“http://www.w3.org/1999/xhtml” xml:lang=“en” lang=“en”>

in the head of your layout file.

You define forms using  “semantic_form_for” like so…

<% semantic_form_for @user do |f| >
<
f.inputs do >
<
= f.input :login, :label => “Username”, :hint => “Something short because it’s in the url”%>
<% end >
<
= f.buttons >
<
end %>

As per usual, there are a myriad of configuration options which can be overridden if necessary. Consult the documentation at Justin French’s Github account for specifics.

TODO and Custom Annotations in Rails Applications

August 22nd, 2010 by Sean Behan

While writing software it’s common to leave comments for your future self. For instance, if you have written some code but realize that it should be refactored to be more efficient, you may place something along the lines of "TODO: change active record find method and replace w/ a custom sql select finder ". With rails, if you follow this convention, you can get a list of your annotations with a rake task.


rake notes:todo

which will print out the file where the the todo was found along with the line number and the comment…

app/controllers/application_controller.rb:

  • [ 8] fix me

Rails defines several other annotation types for you

rake notes # Enumerate all annotations
rake notes:fixme # Enumerate all FIXME annotations
rake notes:optimize # Enumerate all OPTIMIZE annotations
rake notes:todo # Enumerate all TODO annotations

And you also may define your own

	
  • SEAN: please rewrite this method to query only chunky bacon

  • you may find all instances of “SEAN” by running

    rake notes:custom ANNOTATION=SEAN

    Load All ActiveRecord::Base Model Classes in Rails Application

    August 19th, 2010 by Sean Behan

    Here is a simple rake task which will instantiate all of your Active Record models, provided that they are located in the RAILS_ROOT/app/models directory. Interestingly, all plugin models are instantiated by default when you run the task, for instance, if you are using the Acts As Taggable On plugin, you have access to Tag, Tagging without having to include the plugin models directory path to the task.


    namespace :load_ar do
    desc “load up all active record models”
    task :models => :environment do
    models = ActiveRecord::Base.send(:subclasses)
    Dir[“#{RAILS_ROOT}/app/models/*”].each do |file|
    model = File.basename(file, “.*”).classify
    models << model unless models.include?(model)
    end
    end
    end

    If your’re in the console, you can get all the load paths for your Active Record models with the following from the API.
     
    Rails.configuration.load_paths.each do |path|
    p path
    end

    How Beautiful is Ruby?

    August 10th, 2010 by Sean Behan

    Working with Ruby and in particular Rails, it’s easy to take the beauty inherent in the language for granted. I mean look at this code. If you read it aloud to yourself, it reads like an english sentence that any non programmer can understand.


    Forum.categories.map do |category|
    link_to category.name, category
    end.to_sentence

    Forum categories map do category, link to category name, the category, end and convert to a sentence. The code returns a an english sentence as well.

    Fish, French Bread, Coffee and Hamburgers with each linked to the correct resource as well!

    Deploying to Dreamhost

    August 9th, 2010 by Sean Behan

    Remember to include the host declaration in the database.yml file when you deploy to Dreamhost. Dreamhost does not use “localhost” which is typically the default setting when using the mysql adapter and developing locally or even on a small site.

    At least for me, when I ported a Rails app to Dreamhost, this was the only “Gotcha”, because my log files were not reporting any errors and were instead serving the 500 something went wrong file.
    A sample config/database.yml file


    production:
    adapter: mysql
    username: youruser
    password: yourpasswd
    database: ror_production_db
    host: mysql.yourdomain.com

    To port, I unpack my gems, if I haven’t already


    rake gems:unpack

    Then I freeze and package rails w/ my app just in case versions aren’t exact

    rake rails:freeze:gems

    Then I upload to Dreamhost!

    oh russian text, i thought you had something valuable to share...

    August 8th, 2010 by Sean Behan

    but no, you were only clever enough to use your native tongue in an attempt to fool me into publishing your funny, spam comment! thanks to google.com/translate, you were foiled in your plot to usurp traffic from my site

    Matt Mullenweg is Wrong. Thesis Should Carry Whatever License It Wants.

    August 2nd, 2010 by Sean Behan

    There is a debate underway about the legality of Thesis, a popular, paid for Wordpress theme, using a different license than the one Wordpress uses, which is the GPL. Matt Mullenweg, founder of Wordpress, contends that all themes for the platform should inherit the Wordpress license and should be considered a part of the platform. Chris Pearson, creator of Thesis, obviously has a different opinion. There have been many heated debates over the topic, but I haven’t heard an argument by either side that is compelling one way or the other.

    My opinion, which I obviously think is compelling, though is not in any way rooted in any facet of the law or articulated in any legalese whatsoever, is that Matt Mullenweg is wrong. I love what Matt has done. I use and love the Wordpress platform. I also think that his position is noble and rooted in the greater good for the Wordpress community and open source in general.

    I think what has been overlooked in his argument is an assumption we have about software, namely how it is supposed to work and what defines working software in relation to a pluggable software stack, such as Wordpress. Technically, I could create an empty my-new-index.php file, place it inside the Wordpress directory structure, and I have extended the platform. According to Matt, my software which does nothing, must inherit the Wordpress license. Now if I want to sell (or redistribute) this do nothing piece of software for $50.00 (available upon request) I must also sell it with the GPL license. So technically, any piece of PHP code can placed inside of the Wordpress directory structure and therefore, all PHP code must also carry the Wordpress license!?!

    There is obviously some rational limit and discretion available to us so that this sort of thing won’t ever happen!  We could say because the Thesis theme makes use of the Wordpress API, it must be intended for use with Wordpress. However, the Wordpress API is a bunch of PHP functions and Wordpress  itself uses the PHP API, which carries a different license (The PHP License). Which one takes precedence (if they were conflicting) ? Do all PHP applications, because they all must, by definition, use the PHP API, have to inherit the PHP License? This would be ridiculous and I’ve never seen a PHP app with the PHP license, so clearly using an API can’t include licensing requirements, so long as you aren’t modifying and redistributing the original API itself. For example, if I use a PEAR class, I don’t have to inherit the license for all of my work, I just can’t change the license of that class and or modify the original code without making it available again.  Thesis doesn’t (to my knowledge) modify or extend any of the Wordpress core. It provides interface enhancements, outputted HTML generated not by Wordpress, but by Thesis. Wordpress just consumes the Thesis software because it exists in a certain location, placed by someone into the Wordpress directory structure.

    This is the nature of pluggable systems, or software stacks. They are meant to be interoperable with other pieces of software whose parts and purposes are not known ahead of time. This covers a lot of space, space that isn’t even in existence and which it would, if Matt were correct, claim licensing rights to, in the event “it” comes into existence and “works” with said piece of software. Clearly Thesis “works” with Wordpress. But so does a blank file. I intend for that file to do nothing, and it performs (quite efficiently) that task!

    At the end of the day, it is only because Thesis is marketed to the Wordpress community and is intended to be used with the Wordpress platform, that there is an argument about how the software should be licensed. But Thesis is not sold bundled with Wordpress, nor is anyone who purchases it required to use it with Wordpress. For all intents and purposes, it is a stand alone piece of code, that well, does nothing important or worthwhile. Can you really license functionality that may or may not exist depending on how the purchaser decides to implement their purchase, just like my overpriced(though well worth the investment), blank PHP file could be used in any PHP application?

    I have a lot of questions (I haven’t read all the licenses either, so I may be in total error :). Though from what I’ve read and heard so far, it is only because we have an expectation of how the software will work when it is in the Wordpress directory structure that there is a conflict with how Chris has licensed Thesis. This expectation is set by the marketing of the software, not necessarily the software itself. Aside from Trademark infringement, does the language used to sell a product carry over into the the actual license the code must carry? This wouldn’t make sense. Say for instance, “Runs on Windows”, would require another license too?

    I think we’re going to see a lot more arguments over licensing conflicts like what we’re seeing with Wordpress/Thesis. Software is the biggest it has ever been. Open Source software is integrated into the business world like never before and business models are built on top of many of the various projects which are out there, “free” to use. As this space expands, no doubt more and more gray areas will as well.

    On a practical note, what would stop Chris from writing a simple wrapper around the Wordpress API his files use, license this with the GPL, use his wrapper functions instead from inside Thesis and then keep the current Thesis license?

    How to Import/Export Your Wordpress Blogroll... er, Your Links

    July 30th, 2010 by Sean Behan

    It’s not immediately apparent how to import/export the links in your Wordpress blogroll. One would expect that the import/export tool, used to backup/restore Wordpress posts and pages would handle this functionality as well. But the import/export tool has many options. You need to select the Blogroll import option (located near the top of the list) and provide the tool with either the destination of a valid OPML XML url, or upload a valid OPML XML file. If you’re running on Wordpress, this can be found by appending a “/wp-links-opml.php” to the URL of your domain. For example, http://seanbehan.com/wp-links-opml.php will show you my blogroll in XML. If your running out of a subdirectory, don’t forget to include that path in the URL.

    If for some reason you’re running a development website on your localhost, obviously the live, remote site will not be able to contact your localhost for the data. You will have to upload the XML file to the remote site. The Wordpress export tool does not provide the means to generate a the OPML XML file for you. You will have to visit the /wp-links-opml.php file and download the contents yourself, but this depends on how your browser handles XML files. Firefox will show you the raw XML, however, Safari will show you the contents of the XML nodes… which will most likely be only the name of your website. You’ll need to go to “View Source” option to see the actual XML code.Copy and past the XML to a file with the .xml file extension somewhere on your hard drive. Visit the import > blogroll tool and upload the file!

    A simple way to download the file contents is to use the command line web browser Lynx. http://en.wikipedia.org/wiki/Lynx_%28web_browser%29

    Just give Lynx the destination URL and the file to write to (it doesn’t have to exist) and then you can upload this file

    <pre>

    lynx -source URL > my-links.xml

    </pre>

    More info on lynx available here: http://kb.iu.edu/data/aczi.html

    How to Check if the Current Logged In User can Edit a Course in MOODLE Using the Has_capability Function

    July 30th, 2010 by Sean Behan

    After an hour of fruitless searching through the docs and forums, I finally found an answer to my simple question, of course buried in the depths of the shark infested, murky water that is the Moodle code base .

    How do I check if a user is a course creator for a given course? I’m still not 100% sure, the access control policy seems needlessly confusing on first glance and even after reading the heady and mostly pointless, expose on how roles/perms are calculated (Available Here: http://docs.moodle.org/en/How_permissions_are_calculated ) If you notice the section titled “Some Practical Examples” is 100% empty! (I’ve added my code to the wiki so not 100% empty any longer) The most useful part of the docs are completely empty! Instead boatloads of time went into a treatise on the internals and lovely graphs like this one

    But you could always hop into the forum dedicated just to this chunk of the code base (Available here: http://moodle.org/mod/forum/view.php?f=941&page=0) and search through the 500 topics w/ 5000+(i didn’t actually count) nested discussions (including version 1.7 of moodle as well).

    No, instead, ACK came to the rescue and I found a snippet that performed the task.

    Without further ado

    $context = get_context_instance(CONTEXT_COURSE, $course->id);
    if (has_capability(‘moodle/course:update’, $coursecontext)) {
    /** do stuff here */
    }

    There it is. That could have saved me an hour if mentioned in the docs!

    Moodle's Most Important Function Gets No Attention

    July 28th, 2010 by Sean Behan

    Arguably the most important function in the Moodle API, is the create_course function. One would think… after all Moodle is an LMS. Courses are the bread and butter for course management platforms, right? Taking a look at the function in the course/lib.php file reveals almost nothing about the function! WTF? … btw, the function starts at line 3260

    /**

    • Create a course and either return a $course object or false
      *
    • @param object $data – all the data needed for an entry in the ‘course’ table
      /
      function create_course($data) {
      global $CFG, $USER;
      /
      * omitted for your sanity */
      }

    Wow, I think I know less about this function now than before I went digging into the code. How do I assign a teacher to my new course, how do I populate the data object it takes as a parameter (is there a course setup function)? Since courses aren’t really objects in Moodle (just glorified arrays), am I just supposed to set them up by hand… $object->param = val?  Are there default values and/or required attributes that need to be set, otherwise my program is going to come to a halt? What about student enrollments? No example to help for how one might actually use this function? Do I have to really read through the code, starting at around line 3260, then jump between the rest of  this monstrous 4000 line piece of spaghetti coded file and try and make sense of it works (somehow).

    How is it possible that the most important function (since the core problem Moodle solves is creating courses) in the entire application has no meaningful documentation? I think I have an answer. The entire code base is soooo convoluted and a giant waste of CPU cycles, that it would too embarrassing to actually document how it even works.

    Recursively Zip Up a Directory while Excluding Certain Files Based on File Extension Type

    July 21st, 2010 by Sean Behan

    In the example below, I’m going to zip up a directory that includes images in both PNG and PSD file formats. However, I want to exclude the PSDs because they are huge!


    zip -r my-compressed-dir-without-psd.zip directory-to-zip -x ‘*.psd’

    Uncompress A Bz2 File Using Tar Command

    July 10th, 2010 by Sean Behan

    Uncompress a bz2 file using tar command


    tar —use-compress-program bzip2 -xvf your-file-to-uncompress.tar.bz2

    @source http://www.kde.gr.jp/help/doc/kdebase/doc/khelpcenter/faq/HTML/bzip2.html

    Convert Array to Object in PHP

    July 5th, 2010 by Sean Behan
    function array2obj($data) {
        return is_array($data) ? (object) array_map(__FUNCTION__,$data) : $data;
    }
    

    Source: http://www.serversidemagazine.com/php/how-to-convert-array-notation-to-object-notation

    Get Child Categories of Parent Category on Single Post in Wordpress

    June 17th, 2010 by Sean Behan

    I was hoping to find a function in the Wordpress API, that goes something like this…


    the_child_categories(“Vermont”);
    // print Burlington, Brattleboro… etc if this post has any child categories of Vermont

    But I could not. The result that I did find, from various forums goes something like this…


    $parentcat = get_category_by_slug(‘Vermont’);
    foreach((get_the_category()) as $childcat):
    if (cat_is_ancestor_of($parentcat, $childcat)):
    echo get_category_link($childcat→cat_ID);
    echo $childcat→cat_name;
    endif;
    endforeach;

    If you’re in the in the Loop, you can use the get_the_category() function to retrieve the category objects of the current post, without printing the results to the screen. You can loop over the contents from what is returned by the function.

    This condition uses the API function “cat_is_ancestor_of” to check whether or not the category from the current post is a child of the parent which we fetched with the “get_category_by_slug” function.

    Here is a little function that I threw into “functions.php” so that I can get the child categories easily in my theme.


    /** Usage
    _the_category_children(“Vermont”); */
    function the_category_children($slug=""){
    if($categories = get_the_category()):
    if($slug_category = get_category_by_slug($slug)):
    foreach($categories as $category):
    echo (cat_is_ancestor_of($slug_category, $category)) ? $category→cat
    name : ’’;
    endforeach;
    endif;
    endif;
    }

    More info/references on accomplishing this functionality are available
    http://codex.wordpress.org/Function_Reference/cat_is_ancestor_of
    http://wordpress.org/support/topic/284057?replies=8#post-1120489
    http://wordpress.org/support/topic/297615

    How To Flush Your Permalink Structure in Wordpress When Using Taxonomies ...or Wordpress Taxonomies Not Working Instead I See A 404 Page

    June 15th, 2010 by Sean Behan

    I didn’t know this, but because of a linking problem using custom taxonomies in Wordpress, I was forced to find out. If you create a new taxonomy, it will not work immediately on the front facing end. Your users will be greeted by a 404, page not found instead. This isn’t ideal for obvious reasons.

    You create and/or register custom taxonomies like so. You may have multiple taxonomies.


    add_action(‘init’, ‘create_my_taxonomy’, 0);
    function create_my_taxonomy(){
    register_taxonomy( ‘musicians’,
    ‘post’,
    array(
    ‘hierarchical’ => false,
    ‘label’ => ‘People who play lovely music that I like…’,
    ‘query_var’ => ‘musicians’,
    ‘rewrite’ => array(‘slug’=>’musicians’)
    )
    );
    }

    In your theme directory you need at “taxonomy.php” file. This will catch your custom taxonomy requests. You can get even more fancy and create a file like so “taxonomy-musicians.php” which you can use to differentiate your taxonomies look/feel. Nice and slick… however, you may be frustrated after following these two steps and be greeted with a friendly 404 page not found template instead.

    Fear not, you need only visit the Admin >> Settings >> Permalinks page as a logged in admin to flush your rewrite rules and get linking and your correct custom taxonomy template file. Straight forward, unless if you didn’t know that merely visiting the Permalinks Settings page would correct the problem. But Alas, you do!

    Addendum

    You must also have posts using the taxonomy! Otherwise, you will still get the page 404 not found! I’m not sure if there is a work around for this at the moment. Anyone know?

    Render Partial if File Exists

    June 12th, 2010 by Sean Behan

    If you ever want to render a partial but don’t want an error thrown you can either check for the existence of the file first


    <%= render :partial => params[:controller]“/sidebar” if File.exists?(RAILS_ROOT“/app/views/”params[:controller]“/_sidebar.html.erb”) %>

    or you can catch the error that Rails throws


    <%= render :partial => params[:controller]+"/sidebar" rescue nil %>

    My Review of Moodle 1.9 Extension Development

    June 4th, 2010 by Sean Behan

    I wrote a review for Joseph Thibault’s Moodle News on extension development for Moodle. The book is quite good and I think an essential resource for anyone wanting to develop in Moodle. The book focuses on plugin development, but it will also give you an overview of the architecture, api and best practices.

    I wish I had this book about 3 years ago when I first started fooling around in the code base! At any rate, you can read the review on Moodle News at http://www.moodlenews.com/2010/moodle-1-9-extension-development-review-by-bseanvt/

    There is also an interesting discussion underway about the ‘bloat’ in the Moodle code at http://www.moodlenews.com/2010/opinion-1000000-lines-of-code/

    NO Table Cell Spacing Please

    May 27th, 2010 by Sean Behan

    Remove cell padding on a table you add the cellspacing attribute and set it to “0”. Is there a better way to do this with straight up CSS? Nothing seems to work…


    <table id=‘my-favorite-table’ cellspacing=“0” >

    Offset an Element with Relative Position Property with CSS Without Taking Up Any Space in the Document

    May 22nd, 2010 by Sean Behan

    Using CSS positioning it’s possible to offset an element and collapse its width and height where it would normally appear. Wrapping the content in an absolute positioned element, the space that the element would normally take up is collapsed.

    &lt;div style='position:relative;top:-10px;left:-100px;color:blue;width:50px;'&gt;
      &lt;div style='position:absolute;top:0px;left:0px;'&gt;
          Position of this element will be -100px from the left and -10px from the top. Because it is wrapped
          by an absolute positioned element, the original location of this element will be collapsed.
       &lt;/div&gt;
    &lt;/div&gt;
    

    Here is an example

    [this is where the div should be]



    Position of this element will be -100px from the left and -10px from the top. Because it is wrapped
    by an absolute positioned element, the original location of this element will be collapsed.

    but we see that this block of text is next in line instead!

    Postlearn Job Board

    May 20th, 2010 by Sean Behan

    Postlearn is a job board focused on delivering quality jobs listings to people in education.

    An affiliate program is available to bloggers and site owners in the edu space. Bloggers who participate receive a percentage of referrer sales. A widget displaying the most recent jobs increases visibility for Postlearn customers and provides valuable content to affiliate readers. Statistics of widget impressions and affiliate revenue information are presented to affiliates. It is 100% free to become a Postlearn affiliate.

    The site is built with Ruby on Rails, MySQL and several Ruby Gems.

    Workshop Dog

    May 20th, 2010 by Sean Behan

    Workshop Dog is a free events calendar for dog training workshops and group lessons.

    Users can list their training workshops as well as create a business profile. Jobs may be posted to the site for a small fee. Events that are created are distributed to Facebook fan page and twitter account @workshopdogs.

    The site is built using Ruby on Rails and MySQL.

    Natural Dog Training Buzz

    May 20th, 2010 by Sean Behan

    NDT Buzz is a companion news site to Natural Dog Training.

    News and information about Natural Dog Training is generated on the web from many different sources. Blogs, tweets and comments are aggregated using the Feedzirra Ruby Gem. The site lets NDT users keep tabs on the latest info from one location.

    The site is built on Ruby on Rails, Feedzirra and MySQL

    Natural Dog Training

    May 20th, 2010 by Sean Behan

    Natural Dog Training uses Wordpress to run a blog and content management system.

    Custom design, theme and plugin development

    Launch Photoshop (Or Any App) From The Command Line on Mac OS X

    May 18th, 2010 by Sean Behan

    I often find myself coding with the terminal open. Cding around a web app project I usually end up at some point launching Photoshop. Either to touch up or work on a psd, png, jpg …etc. I fire up Photoshop and then navigate to the app’s public directory, where the site images are kept. Then begins the hunt in finder for the image. This takes some time and if I’m already at the command line it would be nice to launch Photoshop with the exact file I want with a single command! To accomplish this just make an alias in your bash profile like so…


    #fire up your text editor and edit your profile
    vim ~/.bash_profile
    #create the alias command
    alias psd=“open -a /Applications/Adobe\ Photoshop\ Elements\ 3/Photoshop\ Elements\ 3.app”

    You need to fire up a new terminal instance before this setting will take place. CMD+N.
    Then from the command line type

    psd my-image.psd

    Note, I didn’t use “ps” as the alias because this is already taken by the system. Also the path to the application may be different on your system. Make sure you use the correct path or you may have an error like

    LSOpenFromURLSpec() failed with error -10827 for the file…

    Programmatically Turn Off Comments in Wordpress with Filter

    May 4th, 2010 by Sean Behan

    To turn comments off programmatically with a filter in Wordpress, you can set the post object’s comment_status variable to “closed”. Call the filter at some point after the post is loaded but before the comments are rendered. This is a hack, but I haven’t seen a simpler approach, beside installing another plugin. In the example below, the condition to disable comments is simple. If a post is in a certain category, comments aren’t allowed. Otherwise, go ahead and behave as normal. You can still disable comments on a per post basis in other categories.

    One thing to note is the use of the global $post object. The function needs access to the object to set the variable.


    add_filter(‘get_header’, ‘sb_turn_comments_off’);
    function sb_turn_comments_off(){
    if(in_category(“Projects”) AND is_single() ){
    global $post;
    $post→comment_status=“closed”;
    }
    }

    I’ve only tested this with the Thematic framework. I assume that other themes will check the comment_status variable before allowing comments.

    Intercepting the Wordpress Loop with Pre_get_posts

    April 22nd, 2010 by Sean Behan

    #deprecated (see http://codex.wordpress.org/Function_Reference/query_posts#Post_.26_Page_Parameters)

    Using the “pre_get_posts” filter you can intercept the Wordpress loop and override or set attributes in the “$query” object. This is useful because you can select just the posts you want, say for instance on your homepage you want to show posts from just one category.

    add_filter(‘pre_get_posts’, ‘filter_homepage_posts’);
    function filter_homepage_posts($query) {
    $limit_number_of_posts = 5;
    $featured_category_id = get_cat_id(‘Reviews’); // by cat name…
    if ($query->is_home) {
    $query->set(‘cat’, $featured_category_id);
    $query->set(‘showposts’, $limit_number_of_posts);
    }
    return $query;
    }

    Thematic Function Reference

    April 19th, 2010 by Sean Behan

    I could not find a listing of all thematic theme functions for Wordpress online. So the following is just a recursive grep of the thematic directory.

    grep -rh “function thematic_” *

    Each function needs to prepended with “thematic_” when adding as a action or filter eto a Wordpress childtheme. Example

    function my_function_says_hello(){ print “Hello!”; }
    add_filter(‘thematic_abovepagebottom’, ‘my_function_says_hello’);

    Here is the list
    remove_generators()
    abovecomments()
    abovecommentslist()
    belowcommentslist()
    abovetrackbackslist()
    belowtrackbackslist()
    abovecommentsform()
    show_subscription_checkbox()
    belowcommentsform()
    show_manual_subscription_form()
    belowcomments()
    singlecomment_text()
    multiplecomments_text()
    postcomment_text()
    postreply_text()
    commentbox_text()
    commentbutton_text()
    commenter_link()
    comments_template()
    include_comments()
    abovecontainer()
    archives()
    navigation_above()
    navigation_below()
    above_indexloop()
    archiveloop()
    authorloop()
    categoryloop()
    indexloop()
    searchloop()
    singlepost()
    tagloop()
    below_indexloop()
    above_categoryloop()
    below_categoryloop()
    above_searchloop()
    below_searchloop()
    above_tagloop()
    below_tagloop()
    belowcontainer()
    page_title()
    nav_above()
    archive_loop()
    author_loop()
    category_loop()
    index_loop()
    single_post()
    search_loop()
    tag_loop()
    time_title()
    time_display()
    postheader()
    postheader_posteditlink()
    postheader_posttitle()
    postheader_postmeta()
    postmeta_authorlink()
    postmeta_entrydate()
    postmeta_editlink()
    content()
    archivesopen()
    category_archives()
    monthly_archives()
    archivesclose()
    404()
    404_content()
    postfooter()
    postfooter_posteditlink()
    postfooter_postcategory()
    postfooter_posttags()
    postfooter_postcomments()
    postfooter_postconnect()
    nav_below()
    previous_post_link()
    next_post_link()
    author_info_avatar()
    cats_meow($glue)
    tag_ur_it($glue)
    comments($comment, $args, $depth)
    pings($comment, $args, $depth)
    body_class( $print = true )
    post_class( $print = true )
    comment_class( $print = true )
    date_classes( $t, &$c, $p = ‘’ )
    abovefooter()
    footer()
    footertext($thm_footertext)
    belowfooter()
    after()
    subsidiaries()
    siteinfoopen()
    siteinfo()
    siteinfoclose()
    create_doctype()
    head_profile()
    doctitle()
    create_contenttype()
    seo()
    canonical_url()
    use_excerpt()
    use_autoexcerpt()
    create_description()
    show_description()
    create_robots()
    show_robots()
    create_stylesheet()
    show_rss()
    show_commentsrss()
    show_pingback()
    show_commentreply()
    head_scripts()
    add_menuclass($ulclass)
    before()
    aboveheader()
    header()
    brandingopen()
    blogtitle()
    blogdescription()
    brandingclose()
    access()
    belowheader()
    trim_excerpt($text)
    the_excerpt($deprecated = ’’)
    excerpt_rss()
    tag_query()
    sidebar()
    abovemainasides()
    betweenmainasides()
    belowmainasides()
    aboveindextop()
    belowindextop()
    aboveindexinsert()
    belowindexinsert()
    aboveindexbottom()
    belowindexbottom()
    abovesingletop()
    belowsingletop()
    abovesingleinsert()
    belowsingleinsert()
    abovesinglebottom()
    belowsinglebottom()
    abovepagetop()
    belowpagetop()
    abovepagebottom()
    belowpagebottom()
    abovesubasides()
    belowsubasides()
    subsidiaryopen()
    before_first_sub()
    between_firstsecond_sub()
    between_secondthird_sub()
    after_third_sub()
    subsidiaryclose()
    search_form()
    widgets_init()
    sort_widgetized_areas($content)
    primary_aside()
    secondary_aside()
    1st_subsidiary_aside()
    2nd_subsidiary_aside()
    3rd_subsidiary_aside()
    index_top()
    index_insert()
    index_bottom()
    single_top()
    single_insert()
    single_bottom()
    page_top()
    page_bottom()
    before_widget_area($hook)
    after_widget_area($hook)
    before_widget()
    after_widget()
    before_title()
    after_title()

    Thematic is a nice theme framework for Wordpress. More info is available at the developers website ThemeShaper. Using the above filters it is possible to create a highly customized child theme quickly.

    Very Simple Breadcrumb Navigation in Rails with Before_filter

    April 16th, 2010 by Sean Behan

    This may not be the ideal solution. This just manages request.referers in a session variable, then looping over each unique path prints a link to the screen. It’s more of a “history” than a hierarchy for resources in an application. It is however, pretty straight forward to implement.

    First create a before_filter in your application controller.Call it on every action. In the definition we’ll parse the request.referer variable with the URI::parse method so that we’re only dealing with the relative, not absolute, resource. We’ll make sure that we’re only storing unique paths and if the user arrives at an index action, we set the session[:breadcrumbs] variable to nil. This indicates that they are at the top level.


    #app/controllers/application_contoller.rb
    #…
    before_filter :setup_breadcrumb_navigation
    protected
    def setup_breadcrumb_navigation
    if params[:action] == “index”
    session[:breadcrumbs] = nil
    else
    url = URI::parse request.referer
    if session[:breadcrumbs].nil?
    session[:breadcrumbs] = url.path.strip
    else
    session[:breadcrumbs] = session[:breadcrumbs] + ", “+url.path if session[:breadcrumb]
    end
    session[:breadcrumbs] = session[:breadcrumbs].split(”, “).uniq.join(”,")
    end
    end
    end

    The helper function just splits apart the string stored in the session[:breadcrumbs] variable, looping over the relative paths. We link to them, but first replace the ugly “/” and preface the display with some form of delimiter. I chose to use the “::” which looks nice to me.


    #app/helpers/application_helper.rb
    def breadcrumbs
    content_tag :span, :id=>"breadcrumbs" do
    if not session[:breadcrumbs].blank?
    session[:breadcrumbs].split(“,”).uniq.map{ |breadcrumb|
    link_to(" :: “+breadcrumb.to_s.gsub(”/“,” “)+”",breadcrumb)
    }
    end
    end
    end

    This is definitely a hack. You won’t necessarily find a hierarchical relationship between links in the breadcrumb navigation. However, it will display the users history letting them quickly access a resource they just visited a page or two before. It’s perhaps 80% of the functionality for only 5% of the work.

    Oh yeah, putting this in a view

    1. app/views/layouts/application.html.erb
      <%= breadcrumbs %>

    Yield a Block within Rails Helper Method with Multiple Content_tags Using Concat

    April 9th, 2010 by Sean Behan

    To clean up some repetitive html coding in views, pass a block of text to a helper function which will wrap it for you the same way, each and every time. For example, I have a ‘help’ link which will toggle the display of a block of text if a link is clicked. I use this “+/- help” link throughout my application in various views. I could create a partial but this gets messy. Instead this is what I want to write in my views…

    &lt;% help do %&gt;
      here is my help text...
    &lt;% end %&gt;
    

    which will render HTML similar to this…


    <a href=‘#’ ‘class=’help’ id=‘help_link_123456’ onclick=‘some_func_to_toggle_state’>+/- help</a>
    <div id=“help_123456”>
    here is my help text…
    </div>

    In order to accomplish this you need to create a helper method. Assigning a unique id, just a random number, will help avoid collisions with the state of the toggled div if you use this more than once per page. Placing other HTML helper methods inside the concat() method allows multiple tags as well as rendering the block passed to the function in the appropriate place. It looks a little unwieldy, but works nicely.

    1. app/helpers/application_helper.rb
      module ApplicationHelper
      def help(&block)
      uniqid = rand; concat( link_to_function(“+/- help”) do |page|
      page[“help_#{uniqid}”].toggle
      page.visual_effect :highlight, “help_#{uniqid}”
      end + content_tag(:div,:class=>"help",:id=>"help_#{uniqid}", :style=>"display:none") do
      yield
      end )
      end
      end

    Nesting Resources in Rails Routes.Rb with Namespaces

    April 8th, 2010 by Sean Behan

    When I have a controller that takes more than one has_many argument, I think about creating a namespace. This way I may still use my forums, pages controllers w/out needing any conditional logic, testing for the presence of :course_id in the params hash.

    #config/routes.rb
    map.namespace :courses, :path_prefix=&gt;'/courses/:course_id' do |courses|
      courses.resources :forums
      courses.resources :pages
    end
    
    map.resources :courses
    map.resources :forums
    map.resources :pages
    
    # some view.html.erb
    &lt;%= courses_forums_path(1) %&gt; /courses/1/forums
    &lt;%= courses_pages_path(2) %&gt; /courses/2/pages
    # w/ use in a form don't forget to pass an array instead of just the resource (will map to forums_controller)
    &lt;%=form_for [:courses, Forum.new] do |f| %&gt;&lt;%end%&gt;
    

    in the namespaced controller you can extend the parent controller (if you like) to have access to methods coursescontroller defines.

    # app/controllers/courses/forums_controller.rb
    class Courses::ForumsController &lt; CoursesController
     before_filter :require_course_login #defined in parent ../courses_controller.rb
     def index
      end
    end
    

    to use the generator to create namespaced controller

    ./script/generate controller ‘courses/forums’ 

    Rake DB Everything, Dump, Destroy, Create, Load

    April 7th, 2010 by Sean Behan

    I’m a big fan of the yaml_db plugin. But I don’t like running rake db:data:load, only to find that my db columns mismatch my model attributes, thus aborting the data import task. To quickly add/remove columns/attributes from a model and rebuild the database with previous db info, I wrote this simple rake task. It saves model records as yaml in db/seandb.yml, and reloads them in the same task but with the db rebuilt. I nest the save method in begin/rescue so that if there are any conflicts the task will continue.

    This biggest challenge was to get a list of all the active record models in the Rails app. This problem has been posted a lot and I didn’t find an easy solution. For now, I just look in the app/models directory and ‘classify’ and ‘constantize’ the file name. This will load the model so that I can iterate over all the active record subclasses and call the appropriate Model.find(:all) method. I could maybe do the same w/ all files in the Rails.configuration.load_paths, but my models are, at least for now, under app/models. Plugin models are loaded and available from the rake task if you require the :environment.

    It’s as simple as running


    rake db:everything

    SAVEDB = "#{RAILS_ROOT}/db/seandb.yml"
    namespace :db do
       task :everything => [:environment, :spit, :drop, :create, :migrate, :populate] do
         desc "spit out model records as yaml, rebuild the database and repopulate the db"
       end
    
       task :spit do
        Dir["#{RAILS_ROOT}/app/models/*"].each {|file| (File.basename(file,".*").classify.constantize)}
        File.open(SAVEDB, "w") do |f|
          ActiveRecord::Base.send(:subclasses).each do |model|
            begin
              model.find(:all).each do |record|
                  f.write(record.to_yaml)
                  print "\twrote #{record.class}\n"
              end
            rescue
            end
          end
        end
       end
    
       task :populate do
        File.open( SAVEDB ) do |yf|
          YAML.each_document( yf ) do |ydoc|
            begin
              m = ydoc.clone
              m.save
              p "...saved #{m.id}"
            rescue
            end
          end
        end
       end
    end
    

    Active Record Find Methods

    March 31st, 2010 by Sean Behan

    Active Record find methods for selecting range from http://charlesmaxwood.com/notes-from-reading-activerecordbase/

    Student.find(:all, :conditions => { :grade => 9..12 })
    return a range
    Student.find(:all, :conditions => { :grade => [9,11,12] })
    will return an "in()"
    

    Carrier Email Addresses for Sending SMS over Email

    March 29th, 2010 by Sean Behan

    Just for reference, here are the carrier email addresses for sending email as an SMS. Look up the carrier for the phone in question, then send an email in this format [telephonenumber]@[carrier-name.com]

    Carrier Email to SMS Gateway

    Alltel [10-digit phone number]message.alltel.com Example: 1234567890message.alltel.com
    AT&T (formerly Cingular) [10-digit phone number]txt.att.net [10-digit phone number]mms.att.net (MMS)
    [10-digit phone number]cingularme.com Example: 1234567890txt.att.net
    Boost Mobile [10-digit phone number]myboostmobile.com Example: 1234567890myboostmobile.com
    Nextel (now Sprint Nextel) [10-digit telephone number]messaging.nextel.com Example: 1234567890messaging.nextel.com
    Sprint PCS (now Sprint Nextel) [10-digit phone number]messaging.sprintpcs.com [10-digit phone number]pm.sprint.com (MMS)
    Example: 1234567890@messaging.sprintpcs.com
    T-Mobile [10-digit phone number]tmomail.net Example: 1234567890tmomail.net
    US Cellular [10-digit phone number]email.uscc.net (SMS)
    [10-digit phone number]mms.uscc.net (MMS) Example: 1234567890email.uscc.net
    Verizon [10-digit phone number]vtext.com [10-digit phone number]vzwpix.com (MMS)
    Example: 1234567890@vtext.com
    Virgin Mobile USA [10-digit phone number]vmobl.com Example: 1234567890vmobl.com
    Free Email To SMS Gateways (International + Smaller US)

    These are all I could find from Wikipedia and other sources. If you’re aware of any other ones please share them in comments and I’ll add them to the list.

    Carrier Email to SMS Gateway
    7-11 Speakout (USA GSM) number@cingularme.com
    Airtel (Karnataka, India) number@airtelkk.com
    Airtel Wireless (Montana, USA) number@sms.airtelmontana.com
    Alaska Communications Systems number@msg.acsalaska.com
    Aql number@text.aql.com
    AT&T Enterprise Paging number@page.att.net
    BigRedGiant Mobile Solutions number@tachyonsms.co.uk
    Bell Mobility & Solo Mobile (Canada) number@txt.bell.ca
    BPL Mobile (Mumbai, India) number@bplmobile.com
    Cellular One (Dobson) number@mobile.celloneusa.com
    Cingular (Postpaid) number@cingularme.com
    Centennial Wireless number@cwemail.com
    Cingular (GoPhone prepaid) number@cingularme.com (SMS)
    Claro (Brasil) number@clarotorpedo.com.br
    Claro (Nicaragua) number@ideasclaro-ca.com
    Comcel number@comcel.com.co
    Cricket number@sms.mycricket.com (SMS)
    CTI number@sms.ctimovil.com.ar
    Emtel (Mauritius) number@emtelworld.net
    Fido (Canada) number@fido.ca
    General Communications Inc. number@msg.gci.net
    Globalstar (satellite) number@msg.globalstarusa.com
    Helio number@messaging.sprintpcs.com
    Illinois Valley Cellular number@ivctext.com
    Iridium (satellite) number@msg.iridium.com
    Iusacell number@rek2.com.mx
    i wireless number.iws@iwspcs.net
    Koodo Mobile (Canada) number@msg.koodomobile.com
    LMT (Latvia) number@sms.lmt.lv
    Meteor (Ireland) number@sms.mymeteor.ie
    Mero Mobile (Nepal) 977number@sms.spicenepal.com
    MetroPCS number@mymetropcs.com
    Movicom (Argentina) number@sms.movistar.net.ar
    Mobitel (Sri Lanka) number@sms.mobitel.lk
    Movistar (Colombia) number@movistar.com.co
    MTN (South Africa) number@sms.co.za
    MTS (Canada) number@text.mtsmobility.com
    Nextel (United States) number@messaging.nextel.com
    Nextel (Argentina) TwoWay.11number@nextel.net.ar
    Orange Polska (Poland) 9digit@orange.pl
    Personal (Argentina) number@alertas.personal.com.ar
    Plus GSM (Poland) 48number@text.plusgsm.pl
    President’s Choice (Canada) number@txt.bell.ca
    Qwest number@qwestmp.com
    Rogers (Canada) number@pcs.rogers.com
    SL Interactive (Australia) number@slinteractive.com.au
    Sasktel (Canada) number@sms.sasktel.com
    Setar Mobile email (Aruba) 297
    number@mas.aw
    Suncom number@tms.suncom.com
    T-Mobile (Austria) number@sms.t-mobile.at
    T-Mobile (UK) number@t-mobile.uk.net
    Telus Mobility (Canada) number@msg.telus.com
    Thumb Cellular number@sms.thumbcellular.com
    Tigo (Formerly Ola) number@sms.tigo.com.co
    Tracfone (prepaid) number@mmst5.tracfone.com
    Unicel number@utext.com
    Virgin Mobile (Canada) number@vmobile.ca
    Vodacom (South Africa) number@voda.co.za
    Vodafone (Italy) number@sms.vodafone.it
    YCC number@sms.ycc.ru
    MobiPCS (Hawaii only) number@mobipcs.net

    Why are PHP5 Namespaces Defined Using a Backslash?

    March 29th, 2010 by Sean Behan

    Why are PHP namespaces defined using a backslash? It looks ugly. Unless of course, there is a good reason for the “\”? Does this namespaced code run more efficiently on Windows?

    Since namespaces are new in PHP5 why not take the opportunity to use them when requiring a file?


    namespace(‘my_library_dir’, ‘lib’); // import my_library_dir as lib
    $myClass = new lib::MyClass; // use the class w/ namespace

    Seems a lot simpler and not as ugly. You could namespace old PHP code this way as well. Please enlighten me if I’m off the mark and the implementation of namespaces in PHP5 is a better design than I have suggested!

    Very Basic Git Workflow

    March 27th, 2010 by Sean Behan

    Very, very basic git workflow


    git pull
    git branch dev_branch
    git checkout dev_branch
    #make some changes
    git checkout master
    git merge dev_branch
    git branch -d branch_to_delete
    git push

    Using Module Mixins to Extend Classes and Objects in Ruby

    March 27th, 2010 by Sean Behan

    The module and class below demonstrate how to use instance methods and class methods from “module mixins”. The thing to remember is scope. For instance, to use class methods within instance methods you need to call them from the class itself. This is accomplished something like this “self.class.class_method_you_want_to_call”. The example below should make it more clear. It would be natural to assume using “self.method_name” within your module mixin, because after all, instance methods just work when included this way. However, you need to take an extra step when you want to “extend” the behavior of a class.

    To extend a class with a mixin you use the method “self.included(base)”. This method takes the parent class “base” as an argument. In the method body you use base.extend to attach class methods. Wrapping up class methods in a module is the easiest way to do it.

    module Greeting
      # Instance Methods
      # Usage Martian.new.hello_world
      def hello_world
        "Martian says: Hello " + self.class.planet+"!"
      end
    
      # Class Methods
      # Usage: Martian.planet
      def self.included(base)
        base.extend ClassMethods
      end
      module ClassMethods
        def planet
          "world"
        end
      end
    end
    
    class Martian
      include Greeting
      def self.location
        "Martian lives on "+self.planet
      end
    end
    
    p Martian.new.hello_world
    p Martian.location
    

    Installing RedMine PM Software on Apache with Phusion and REE and Seeing a 404 Page Not Found Error on Installation

    March 27th, 2010 by Sean Behan

    If you follow the instructions on how to install the Rails Redmine PM Software (available here) and are using Apache with Passenger (REE), you need to delete the .htaccess file that is kept in RAILS_ROOT/public directory. Otherwise you’ll see a 404 page not found error. Took me a while to hunt this down. I stopped thinking about .htaccess in Rails apps but I guess REE+Passenger isn’t the default deployment yet.

    Change database column names for form validations in Rails

    March 24th, 2010 by Sean Behan

    When you use validations in Rails, db column names are used as ‘keys’ for error messages. This is usually the preferred way to go about it because this maps nicely to the form fields. However, if you use a virtual attribute this may not be the case. For example, I have a ‘password_crypted’ field in my users table that I don’t want my user to see if they fail to complete the field. Instead of returning “Password crypted cannot be blank” I just want to tell them that a password can’t be blank. If you provide a custom ‘:message’ on the validation this won’t replace the column name. The solution is to override the “human_attribute_name” class method and map specific column names to the string you want to use instead.

    class User &lt; ActiveRecord::Base
      validates_presence_of :password_crypted
      ATTR_NAMES = {:password_crypted => "Password"}
      def self.human_attribute_name(attr)
         ATTR_NAMES[attr.to_sym] || super
      end
    end
    

    I found these resources helpful while I was in search for a solution to this problem.
    http://stackoverflow.com/questions/808547/fully-custom-validation-error-message-with-rails


    http://henrik.nyh.se/2007/12/change-displayed-column-name-in-rails-validation-messages

    Defining Application Constants for Ruby on Rails Application

    March 17th, 2010 by Sean Behan

    The best place to keep application constants which are environment specific is in config/environments directory. For instance…

    1. in RAILS_ROOT/config/environments/development.rb
      APP_DOMAIN = “localhost”
    2. in RAILS_ROOT/config/environments/production.rb
      APP_DOMAIN = “real-domain.com”

    …will set the APP_DOMAIN constant to either “localhost” or “real-domain.com” depending on which environment Rails boots up.

    Adding Public/Private Key Pairs on Mac OS X and Ubuntu for Passwordless Remote SSH Sessions

    March 15th, 2010 by Sean Behan

    On your local machine cd into the .ssh directory in your home “~/” directory. If it doesn’t exist you can create it with “mkdir ~/.ssh”. Next generate your public/private keys and copy the public key to the remote server.


    cd ~/.ssh
    ssh-keygen -t rsa -b 4096

    1. will take a couple seconds but when finished
    2. specify a full path (if there is already an existing key) or hit enter to install to the default location ~/.ssh
    3. when it prompts for a passphrase just hit enter
    4. and enter again when it asks to confirm the passphrase
    5. then we copy the public key the remote server (this assumes you don’t already have an authorized_keys file)
    6. copy and paste the contents of the id_rsa.pub file into the authorized_keys file otherwise
      scp id_rsa.pub user@yourdomain.com:.ssh/authorized_keys

    You’ll need to edit your ssh config file and restart the process to allow for public/private key authentication.

    vim /etc/ssh/ssh_config
  • add or uncomment these two lines
    RSAAuthentication yes
    PubKeyAuthentication yes
  • … and restart
    /etc/init.d/ssh restart
  • Troubleshooting

    A couple of things to keep in mind. 1) Permissions matter. Make sure that your keys are not world readable (this should be secure) Run chmod 400 on authorized_keys file.

    If you had a set of keys already setup in .ssh/ on your local machine and want to install the new keys in another directory so as not to overwrite the old pair, you need to add them to ssh with this command


    ssh-add ~/full/path/to/your/new/keys

    More information is available here http://www.debian-administration.org/articles/152

    Hacking Rails Plugins

    March 12th, 2010 by Sean Behan

    Using the Acts as Taggable On plugin to add categories to a model class, I wanted to override the to_param method and place the name attribute in the url. The plugin, installed as a gem, source shouldn’t need to be hacked in order to accomplish this. The solution is to add a plugin into the RAILS_ROOT/vendor/plugins directory and append the plugin name with _hack. This will, because of an alphabetical load order, allow you to reopen the any class in the plugin. In my example

    # RAILS_ROOT/vendor/plugins/acts_as_taggable_on_hack/init.rb
    Tag.class_eval do
      to_param
        "#{id}-#{name.gsub(/[^a-z0-9]+/i, '-'/)
      end
    end
    

    Got this tip from http://errtheblog.com/posts/67-evil-twin-plugin.

    Setup Wildcard Subdomain on Localhost for Development Work without /Etc/hosts TomFoolery

    March 5th, 2010 by Sean Behan

    Step 1.

    Open up your browser and visit http://www.hexxie.com. You can also go to anything.hexxie.com and everything.hexxie.com, which will resolve to your local machine (assuming it’s localhost at 127.0.0.1).

    How it works


    Super simple. I just pointed hexxie.com and *.hexxie.com to 127.0.0.1, which is your localhost address. If you’re on Rails just append the port number as usual. http://hexxie.com:3000 or on Django http://hexxie.com:8000. Or you can always fire those guys up on port :80 with sudo ./script/server -p80 for Rails
    or sudo django-admin.py runserver 80

    To set up your own just configure DNS to point your domain to 127.0.0.1 for the IP address. No more futzing with /etc/hosts

    Originally got this tip from http://tbaggery.com/2010/03/04/smack-a-ho-st.html who has created his own service at smackaho.st

    The word “Hexe” is German for “Witch”. I have a dog named “Hexxie” after the German word and that is the origin of the domain name hexxie.com, in case you’re wondering.

    Onchange Event Fired from Select Field in Rails Form

    March 4th, 2010 by Sean Behan

    In the view there is a regular Rails form and a javascript function that will be triggered when the country select field is changed. The javascript function will make an ajax request to the country_select url with the country code passed as the id variable, e.g., /country_code/us for the United States. I’m also using the Carmen plugin for this example which will provide a list of countries and their respective states/provinces. Not all countries are full supported. More information on Carmen can be found at http://autonomousmachine.com/2009/4/1/carmen-a-rails-plugin-for-geographic-names-and-abbreviations and http://github.com/jim/carmen

    <%form_for(@model) do |f| >
    <script type=“text/javascript” charset=“utf-8”>
    function change_state_select(state_code)
     {
    new Ajax.Request(‘/country_select/’+state_code,
    {
    method: ‘get’,
    onSuccess: function(transport) {
    $(‘state_select’).replace(transport.responseText);
    }
    });
    }
    </script>
    <
    = f.select :country,
    Carmen::COUNTRIES,
    {},
    { :onchange => “change_state_select(this.options[this.selectedIndex].value);” }
    >
    <div id=‘state_select’></div>

    *Note the : onchange should really be one word but an emoticon shows up otherwise :onchange :(*
    Since not all countries are supported I need to execute some conditional logic in the action country_select. If the country is supported I’ll return a snippet of html containing a select field that my form will use. If the country is not supported I’ll return a text field so that the user can write in their state/province.
    class CountrySelectController < ApplicationController
    def country_selecet
    begin
    @states = Carmen::states(params[:id])
    rescue
    @states = nil
    end
    render :partial => “country_select/states”
    end
    end

    In the final partial that is rendered there is either a select field or a text field
    <div id=“state_select”>
    < if @states.nil? >
    <
    = text_field_tag :model, :state >
    <
    else >
    <
    = select :model, :state, @states%>
    <% end %>
    </div>