Tips from the MountainRB ruby on rails workshop

Yesterday I was at the MountainRB ruby workshop, which was basically an intro to rails class. It was a really good workshop and here are some tips I picked up.

Cucumber

Change the config/cucumber.yml file to display pretty output, making it easier to see the failed step.

default: -format pretty

use Background: in cucumber features for tasks that need to happen for every scenario. Use just like Scenario

Background: Make sure that we have a topic
  Given I go to the topics page
  And I follow "New Topic"
  And I fill in "Title" with "Rails Fixtures" 
  And I fill in "Description" with "Introduce how to add test data with fixtures."
  And I press "Create"

Rails templates

When you create a new rails application you can specify a template that runs after the initial generation. It can handle a lot of the initial setup. Here’s the one used used in the workshop http://gist.github.com/609269.txt

rails new APP_NAME -m TEMPLATE_URL

View a models attributes

From inside the rails console you can view a models attributes by calling class on an instance of the Model.

ruby-1.9.2-p0 > (User.new).class

Routes

rake routes will show the routes defined for the application.

        login        /login(.:format)          {:action=>"new", :controller=>"user_sessions"}
         logout        /logout(.:format)         {:action=>"destroy", :controller=>"user_sessions"}
user_sessions GET    /user_sessions(.:format)  {:action=>"index", :controller=>"user_sessions"
user_sessions POST   /user_sessions(.:format)  {:action=>"create", :controller=>"user_sessions"}

Notes

Rails will cascade saves in a transaction by default

The resource generation option will create the model and migration, while adding a blank controller and empty views directory.

rails generate resource

heroku open shows the current heroku app in the browser.

Resources

http://bit.ly/ruby-resources – Resources from DevChix

http://railsapi.com – Rails documentation

http://boulderruby.org – Boulder user group

http://groups.google.com/group/derailed – Denver user group

http://RailsBridge.org - an inclusive and friendly Ruby on Rails community


Resize/Clone a VirtualBox hard disk with the current snapshot

After wasting a ton of time, I’m noting this here to hopefully help myself or someone else in the future.

Making the new virtual hard disk

In VirtualBox open the virtual media manager and create a new disk with the larger size. Note it’s location.

Open a command prompt to c:\program files\oracle\virtualbox and run

VBoxManage showvminfo <Machine Name>

Find the primary master line, and note the UUID.

Clone that using your UUID and the path to the new disk

VBoxManage clonehd 73880a2b-ba46-459e-b71b-816ceadecb5a c:\users\dusty.virtualbox\harddisks\CloneDisk.vdi –existing

Resize

There may be better instructions elsewhere, but this worked for me.

  1. Attach a Linux live cd to the cdrom of the machine.

  2. Change the hard disk image to your new image file.

  3. Boot

  4. Start GParted

  5. Right click the swap and select swapoff, note the size and delete.

  6. Delete the extended partition.

  7. Resize the primary partition.

  8. Add an extended partition back.

  9. Add a swap partition back.

  10. Apply the changes.

  11. Shutdown, remove the live image from the machine, restart.

Reference:

http://forums.virtualbox.org/viewtopic.php?t=585

http://forums.virtualbox.org/viewtopic.php?f=1&t=791&p=103299#p103299

http://www.attackr.com/resize-an-existing-vdi-virtualbox-image-easily/


WordPress Quick Install and Setup On Ubuntu

Here’s some quick notes for installing WordPress on Ubuntu 10.

Official install doc: http://codex.wordpress.org/Installing_WordPress

I choose hosting on Linode, which has been an awesome experience so far, they have really good help guides too.

Server

You’ll need MySql, PHP, Apache installed.

apt-get install apache2 apache2-doc apache2-utils

apt-get install libapache2-mod-php5 php5 php-pear php5-xcache php5-suhosin php5-mysql

apt-get install mysql-server

Run MySql Secure Installation

mysql_secure_installation

Enable Rewriting

a2enmod rewrite

Enable image support for php.

sudo apt-get install php5-gd

/etc/init.d/apache2 restart

Get It

wget http://wordpress.org/latest.tar.gz > tar -xzvf latest.tar.gz

Database

mysql -u adminusername -p

CREATE DATABASE databasename;
 
GRANT ALL PRIVILEGES ON databasename.* TO "wordpressusername"@"localhost"
IDENTIFIED BY "password";
  
FLUSH PRIVILEGES;

Setup Apache

Create the web root directories

mkdir /var/www/red27.net/public_html -p <br />mkdir /var/www/red27.net/logs

Create an apache virtual host config

See what’s there in the sites-available

ls /etc/apache2/sites-available/

Copy an existing config

cp /etc/apache2/sites-available/candland.net /etc/apache2/sites-available/red27.net

Edit to match the correct location.

vim /etc/apache2/sites-available/red27.net

Copy the WP files to the site root

cp downloads/wordpress/* /var/www/red27.net/public_html/ -r

Change owner

chown -R www-data /var/www/red27.net/public_html/

Config WordPress

Rename the wp-config.php file

mv /var/www/red27.net/public_html/wp-config-sample.php /var/www/red27.net/public_html/wp-config.php

Edit the wp-config.php, set the correct db connection values, and replace the security lines from here

vim /var/www/red27.net/public_html/wp-config.php

Enable the site

a2ensite red27.net

Restart apache

/etc/init.d/apache2 restart

Visit the site and configure WordPress!


AutoTest Powershell Script

This script will watch a source directory for changes, just *.cs files in this case and then execute a script when a change is detected. This handles the issue of the change event being triggered twice for one change. I’m just calling my default Psake script, but you can put any build/test script call in place of it.

function watch-folder {
    param([string]$path, [string]$filter = "*.*", $command)
    get-eventsubscriber -force | unregister-event -force
    $global:lastGen = [datetime]::Now
    $expandedPath = convert-path $path
    write-host "Watching" $expandedPath\$filter
    $fileSystemWatcher = new-object System.IO.FileSystemWatcher
    $fileSystemWatcher.NotifyFilter = [System.IO.NotifyFilters]::LastWrite
    $fileSystemWatcher.Path = $expandedPath
    $fileSystemWatcher.Filter = $filter
    $fileSystemWatcher.IncludeSubdirectories = $true
    $action = {
        $timeGenerated = $event.TimeGenerated

        if ($timeGenerated - $global:lastGen -gt (new-timespan -sec 1)) {
            write-host ***************************************** -foreground Green
            write-host $eventArgs.FullPath -foreground Green
            write-host $eventArgs.ChangeType at $event.TimeGenerated -foreground Green
            write-host TESTING $event.MessageData -foreground Green
            $result = &amp; $event.MessageData | out-string -stream
            if ($LastExitCode -gt 0) {
                $result | select-object -last 70 | out-host
                write-host FAILED -foreground Red
                write-host ***************************************** -foreground Red
            }
            else {
                write-host SUCCESS -foreground Green
                write-host ***************************************** -foreground Green
            }
        }

        $global:lastGen = $timeGenerated
    }
    [void](Register-ObjectEvent -InputObject $fileSystemWatcher -EventName Created -SourceIdentifier ThisFileWatcher -Action $action -MessageData $command)
    [void](Register-ObjectEvent -InputObject $fileSystemWatcher -EventName Changed -SourceIdentifier ThisFileWatcherA -Action $action -MessageData $command)
    [void](Register-ObjectEvent -InputObject $fileSystemWatcher -EventName Deleted -SourceIdentifier ThisFileWatcherB -Action $action -MessageData $command)
}

watch-folder ".\src" "*.cs" {
  psake
}

wait-event "ctrl-c"

Thanks to this post PowerShell, events and file watcher.


ViEmu + ReSharper + VS2010 Review

I’ve been using the ViEmu plugin with ReSharper in VS2010 for a couple of weeks now. Overall, I really like combo. However there are a few things that annoy me with ViEmu. The selections modes are not the same between ViEmu and selecting text with the mouse, looks like a licensed copy might fix that. The replace function is missing the ‘c’ confirm option. The other things are mostly key bindings that ViEmu overrides, this can be changed with the _viemurc file. You need to create that file in the c:\users[username] directory, then add the bindings you’d like. I’ve added some for ReSharpers goto type command, and changed Ctrl+V back to paste.

map <C-n> gS:vsc ReSharper.ReSharper_GotoType<CR>
imap <C-n> gS:vsc ReSharper.ReSharper_GotoType<CR>
map <C-v> gS:vsc Edit.Paste<CR>

BYW, You can find the commands you’re looking for from the VS toos:options:keyboard menu.

I’m think I’m going to get a license for ViEmu, anyone else have any tips for it?


Nhibernate Many-to-many mapping with an Enumeration on One Side

I’m posting this because I was trying to do this in an intuitive way and was thinking about it in the wrong way. A post on StackOverflow,  Map to a list of enums, got me pointed in the right direction.

I prefer using Enum’s in code, in place of database lookup tables, doing this for single properties, it makes sense to just map the Enum value into the database column of the owning entity. However when thinking about mapping many-to-many, for example, the US States a person has visited, and you fall into DB thinking mode. Many-to-many is the solution, unless States is an Enum and that’s all you need. In that case you should think about the problem for the domain side, a person as a list of visited States. In this way, you only need to have a one-to-many relationship, where the many side is the Enum value.

Adding something like the mapping code below to you Person mapping will get a VisitedStates table with a PersonId column and StateId column. No lookup tables needed, of course one could be added to help the DBAs. In the code you have a States list on the Person class.

<bag name="States" cascade="all" table="VisitedStates">
  <key column="PersonId"/>
  <element type="States" column="StateId" />
</bag>

Advantages

  • No mapping table.
  • Lookup data defined in code, as an Enumeration.
  • Less classes and mapping files.
  • Don’t have to worry about updating a lookup table with new values.
  • Don’t have to worry about making a State class with a immutable mapping.

Disadvantages

  • DBAs won’t know the values without maintaining a lookup table (even if it doesn’t get used by code).
  • Can not reorder the Enumeration values without updating the DB.

Other advantages/disadvantages?


PowerVim, setup VIM to use Powershell

[https://candland.net/assets/binary/PowerVimsetupVIMtousePowershell_DAD5/vim_logo_2.png]

I’m using VIM more and more and have come to the point where issuing commands to the shell would be useful, the problem is I use PowerShell. This is fairly easy to setup in VIM, but I did hit two things that needed to be worked around. Script execution issues and my ps profile script changing directories.

First script execution, by default, does not allow custom scripts, like your modified ps profile. This was easy to take care of in the _vimrc file. Here’s what I added to setup PowerShell:

 # change to powershell       
 set shell=powershell.exe\ -ExecutionPolicy\ Unrestricted
 set shellcmdflag=-Command
 set shellpipe=>       
 set shellredir=>

You should also make sure to set your VIM encoding=utf-8. With that in place, PowerShell can be invoked and it will load your profile. However…

My profile always sets the current directory to my projects folder, which is good except when it’s being opened by VIM. Here’s my fix.

if ($HOME -eq $pwd.path) { 
   cd $projects 
}

With those changes in place I can now issue PowerShell commands from within VIM.


Brutalist Framework