Here's my .irbrc file. This is based off of this post by Thoughtbot about using wirble with your IRB.
This gives me auto-completion, history, color, Rails SQL output and a few other conveniences.
Wednesday, 24 December 2008
On the Rails merger with Merb
I think overall it will be a good thing.
There obviously are a lot of common goals between the two frameworks but I'm more interested in how they merge some of the more controversial differences. Both teams have already mentioned modularity and internal APIs as something that Rails is going to adopt, but what about some of the smaller differences?
Some of the more difficult issues to be resolved might be:
I'm certainly looking forward to seeing what they come up with!
There obviously are a lot of common goals between the two frameworks but I'm more interested in how they merge some of the more controversial differences. Both teams have already mentioned modularity and internal APIs as something that Rails is going to adopt, but what about some of the smaller differences?
Some of the more difficult issues to be resolved might be:
- Merb's requirement for an explicit call to render or display - will that be optional?
- Merb's mailer and exception handling - Merb way is probably superior
- Rails' extensive use of monkey patching and magic versus Merb's preference for code simplicity
- Rails' use of test/unit versus Merb's RSpec preference - will all of rails internal tests be rewritten in RSpec?
- slices versus engines - support both??
I'm certainly looking forward to seeing what they come up with!
Sunday, 30 November 2008
Writing User Stories with Merb, Cucumber, merb_cucumber and webrat
I decided to try out cucumber and webrat for writing user stories in my sample merb application. Merbbit is a merb-based web app for community-driven link submission. Think Digg, Reddit etc.
I had used user stories before but I found so time-consuming as to be of little use. I was hoping that using webrat's shortcuts, the new improved story runner Cucumber and factory_girl would speed up writing these tests.
Getting setup was quite pain-free.
This will also install a sample login feature that should pass if you’re using merb-auth. I was using merb-auth but when I ran:
This was because I had changed the login field in the login form from 'login' to 'email'. This was easy to fix. In features/login.feature I just changed
One of the first cool things I notice about cucumber is how much more colourful it is than the original user stories. It also discreetly tells you what line and what file the step starts on. This can be useful when you forget which file you wrote the matching step in.
For the step "And a user with login "me", email "me@example.com" and password "secret_password"" I needed to create a step that would populate the database with a user. I decided to use factory girl
Sources that helped:
http://github.com/david/merb_cucumber/tree/master
http://github.com/brynary/webrat/tree/master
http://rubybling.blogspot.com/2008/10/merbcucumber-almost-baked.html
I had used user stories before but I found so time-consuming as to be of little use. I was hoping that using webrat's shortcuts, the new improved story runner Cucumber and factory_girl would speed up writing these tests.
Getting setup was quite pain-free.
sudo gem install cucumber webrat david-merb_cucumber --no-ri --no-rdoc
merb-gen cucumber --session-type=webrat
This will also install a sample login feature that should pass if you’re using merb-auth. I was using merb-auth but when I ran:
rake featuresThe feature failed with the error:
Could not find field labeled "login"
This was because I had changed the login field in the login form from 'login' to 'email'. This was easy to fix. In features/login.feature I just changed
And I fill in "login" with "i_dont_exist"to
And I filled in "email" with "i_dont_exist"And it worked!
One of the first cool things I notice about cucumber is how much more colourful it is than the original user stories. It also discreetly tells you what line and what file the step starts on. This can be useful when you forget which file you wrote the matching step in.
And I fill in "password" with "and_i_dont_have_a_password" # features/steps/common_webrat.rb:16The failed login scenario of the Login feature comes for free. I now needed to write a successful login scenario.
Scenario: Successful LoginI had to write some new steps before I could run this scenario.
Given I am not authenticated
And an user exists with login "me@example.com" and password "secret_password"
When I go to /login
And I fill in "email" with "me@example.com"
And I fill in "password" with "secret_password"
And I press "Log In"
Then the login request should succeed
And I should see "me" in user_login
For the step "And a user with login "me", email "me@example.com" and password "secret_password"" I needed to create a step that would populate the database with a user. I decided to use factory girl
$ sudo gem install thoughtbot-factory_girl
add require 'factories' to features/env.rb
features/factories.rb:
gem 'thoughtbot-factory_girl'
require 'factory_girl'
Factory.define :user do |u|
u.login 'me'
u.email 'me@example.com'
u.password 'password'
u.password_confirmation 'password'
u.active 'active'
end
require 'features/steps/common_factory_steps'
features/steps/common_factory_steps:For the step "Then the login request should succeed", merb_cucumber comes with a "Then the login request should fail" but not a succeed step. It's easy to create one though.
Given /^a user with login "(.+)", email "(.+)" and password "(.+)"$/ do |login, email, password|
Factory(:user, :login => login, :email => email, :password => password, :password_confirmation => password)
end
Then /^the (.*) ?request should succeed/ do |_|I can't see an easy way using merb to tell if a specific template has been rendered like in rails integration testing (render_template) so I settled for just verifying that the users login "me" appears inside an element called 'user_login'.
response.should be_successful
end
Then /^I should see "(.+)" in (.+)$/ do |message, id|This step could be used to test for any piece of text inside an element with a given id.
response.should have_xpath("//*[@id=\"#{id}\" and text()=\"#{message}\"]")
end
Sources that helped:
http://github.com/david/merb_cucumber/tree/master
http://github.com/brynary/webrat/tree/master
http://rubybling.blogspot.com/2008/10/merbcucumber-almost-baked.html
Friday, 22 February 2008
Emacs Cheat Sheet
I have been trying to learn emacs. Note the use of the word learn. It's not just something you can just use, you have to learn and get used to a heap of things before you can meaningful use it. There are lots of cheatsheets for emacs out there but I want to compile my own one with just the stuff that is most important to me.
The best way to learn emacs is probably by going through a tutorial like this one and the built-in tutorial but what's missing is a quickstart tutorial for emacs...
Here's my attempt:
C-x Ctrl and press x
M-x Meta/Alt key and press x
C-x y Ctrl and press x and then press y
M-x y Meta/Alt key and press x and then press y
Getting Started
Installing on Debian/Ubuntu: sudo apt-get install emacs
Starting a new file (from the commandline):
emacs filename
Starting a new file (from inside Emacs):
C-x b and type the name of your new file
C-h t - start the builtin tutorial
C-g Abort a command
Saving
C-x C-s Save
C-x s Save all (or a few at a time)
Navigation
C-a Beginning of line
C-e End of line
M-f Forward one word
M-b Backward one word
Editing
C-d == DELETE, deletes character to the right
backspace == Deleting, deletes character to the left
M-d Delete word
C-k Delete to the end of the line
C-x u or C-_ Undo (Redo is more complicated)
Cutting, Copying and Pasting
While copying is still copying, what I think 90% of people know as cutting and pasting is not called as such in Emacs. We have Killing and Yanking. Basically kill == cut, yank == paste. (The name yank is a bit counter-intuitive at first I think. It made me assume it was cut. like you were yanking it out of the text, but in fact you're yanking it back into the text.) Emacs also has the concept of a kill-ring. That's just a fancy name for a clipboard.
C-k Kill/Cut to the end of the line
C-SPACEBAR - mark the start of a piece of text followed one one of the following:
M-w Copy
C-w Kill/Cut
C-y Paste (yank)
Find/Replace
C-s Find... (Search) - This does some cool highlighting of matches
C-s C-s Find again
M-% Replace
C-g Abort
Moving between buffers (fancy name for an open file)
C-x b switch-to-buffer. Prompts for a buffer name and switches the buffer of the current window to that buffer.
C-x C-b list-buffers.
C-x k kill-buffer.
Navigating between open windows (split views and stuff)
C-x o other-window. Switch to another window, making it the active window.
C-x 2
C-x C-z - suspend
The best way to learn emacs is probably by going through a tutorial like this one and the built-in tutorial but what's missing is a quickstart tutorial for emacs...
Here's my attempt:
C-x Ctrl and press x
M-x Meta/Alt key and press x
C-x y Ctrl and press x and then press y
M-x y Meta/Alt key and press x and then press y
Getting Started
Installing on Debian/Ubuntu: sudo apt-get install emacs
Starting a new file (from the commandline):
emacs filename
Starting a new file (from inside Emacs):
C-x b and type the name of your new file
C-h t - start the builtin tutorial
C-g Abort a command
Saving
C-x C-s Save
C-x s Save all (or a few at a time)
Navigation
C-a Beginning of line
C-e End of line
M-f Forward one word
M-b Backward one word
Editing
C-d == DELETE, deletes character to the right
backspace == Deleting, deletes character to the left
M-d Delete word
C-k Delete to the end of the line
C-x u or C-_ Undo (Redo is more complicated)
Cutting, Copying and Pasting
While copying is still copying, what I think 90% of people know as cutting and pasting is not called as such in Emacs. We have Killing and Yanking. Basically kill == cut, yank == paste. (The name yank is a bit counter-intuitive at first I think. It made me assume it was cut. like you were yanking it out of the text, but in fact you're yanking it back into the text.) Emacs also has the concept of a kill-ring. That's just a fancy name for a clipboard.
C-k Kill/Cut to the end of the line
C-SPACEBAR - mark the start of a piece of text followed one one of the following:
M-w Copy
C-w Kill/Cut
C-y Paste (yank)
Find/Replace
C-s Find... (Search) - This does some cool highlighting of matches
C-s C-s Find again
M-% Replace
C-g Abort
Moving between buffers (fancy name for an open file)
C-x b switch-to-buffer. Prompts for a buffer name and switches the buffer of the current window to that buffer.
C-x C-b list-buffers.
C-x k kill-buffer.
Navigating between open windows (split views and stuff)
C-x o other-window. Switch to another window, making it the active window.
- C-x 1
delete-other-windows. Deletes all other windows except the current one, making one window on the screen.
delete-window. Deletes just the current windowC-x 2
split-window-vertically
C-x 3 split-window-horizontally
Exiting
C-x C-c - exit, prompts for savesC-x C-z - suspend
Thats all for now!
Friday, 11 January 2008
MERB: Rendering JPEG's from actions
While working on my MERB app, I wanted to pull an image from the database and render it inline as if it were a static jpg. I knew how to do this in Rails but not in MERB. It turns out to be really easy, although quite different from how it is done in Rails.
This blog post was very useful to figuring it out.
Let's suppose you have a database model Image and an Images controller and action 'show'. Firstly at the end of your merb_init.rb file, put the following line:
then in the controller add a provides parameter for jpg and
In your model add a method to_jpg like so.
Where data is the name of the column in your images table that holds the binary data.
Make sure you restart your server after all these changes.
Next your controller should look something like this:
And thats it! If you go to /images/1.jpg (assuming RESTful routing...), the controller will retrieve the image with id 1 and MERB will call the to_jpg method on that object. It will then output that binary image data and send with the correct http header Content-Type parameter.
This blog post was very useful to figuring it out.
Let's suppose you have a database model Image and an Images controller and action 'show'. Firstly at the end of your merb_init.rb file, put the following line:
Merb.add_mime_type(:jpg, :to_jpg, %w[image/jpeg], {})then in the controller add a provides parameter for jpg and
In your model add a method to_jpg like so.
def to_jpeg
data
end
Where data is the name of the column in your images table that holds the binary data.
Make sure you restart your server after all these changes.
Next your controller should look something like this:
class Image < Application
provides :xml, :js, :yaml, :jpg
def show
image = Image.find(params[:id])
render image
end
end
And thats it! If you go to /images/1.jpg (assuming RESTful routing...), the controller will retrieve the image with id 1 and MERB will call the to_jpg method on that object. It will then output that binary image data and send with the correct http header Content-Type parameter.
Thursday, 10 January 2008
Merb Gotchas
I'm gonna to keep this post up to date with any gotchas or "mistakes of understanding" that I make as I work on MERB.
First up. Controllers are called the same as models! Example:
and
So if you create a controller for monkeys and a model for monkeys, the two class names will both be called Monkey, except one will inherit from controller and the other from model.
In fairness to MERB the generators do warn you about this.
But it doesn't explain why it is reserved and maybe I'm just thick but it stumped me for longer than it should have.
You never have a chance to make that mistake in Rails because controllers are always like "MonkeyController". (I don't know why merb didn't follow suit... DRYer? simpler?)
What I did to get around that was to make the controller plural. monkeys.rb
First up. Controllers are called the same as models! Example:
$ script/generate controller monkey
Started merb_init.rb ...
Loading Application...
Compiling routes..
Loaded DEVELOPMENT Environment...
exists app/controllers
create app/controllers/monkey.rb
and
$ script/generate model monkey
Started merb_init.rb ...
Loading Application...
Compiling routes..
Loaded DEVELOPMENT Environment...
exists app/models
create app/models/monkey.rb
So if you create a controller for monkeys and a model for monkeys, the two class names will both be called Monkey, except one will inherit from controller and the other from model.
In fairness to MERB the generators do warn you about this.
"The name 'Monkey' is reserved."But it doesn't explain why it is reserved and maybe I'm just thick but it stumped me for longer than it should have.
You never have a chance to make that mistake in Rails because controllers are always like "MonkeyController". (I don't know why merb didn't follow suit... DRYer? simpler?)
What I did to get around that was to make the controller plural. monkeys.rb
Wednesday, 9 January 2008
Enabling Sessions in MERB
Sessions are disabled by default in MERB (because it makes the performance numbers look great! ;) ). To enable sessions, just set the variable :session_store: in merb.yml to one of activerecord, sequel, datamapper, memory, cookie or mem_cache.
Because I want to use memory for my development sessions and mem_cache for my production environment, I set up config/environments/development.yml and put in:
and config/environments/production.yml and put in:
If you're using memcached with MERB, you need to put
in your merb_init.rb (http://merb.rubyforge.org/classes/Merb/MemCacheSession.html)
Because I want to use memory for my development sessions and mem_cache for my production environment, I set up config/environments/development.yml and put in:
:session_store: memory
:memory_session_ttl: 3600
and config/environments/production.yml and put in:
:session_store: mem_cache
If you're using memcached with MERB, you need to put
require 'memcache'
CACHE = MemCache.new('127.0.0.1:11211', { :namespace => 'my_app' })
in your merb_init.rb (http://merb.rubyforge.org/classes/Merb/MemCacheSession.html)
Tuesday, 8 January 2008
HTTP Authentication for MERB
I've just started working on a new web application. It's going to be quite a simple app but speed and responsiveness is important so I decided to try Merb. I'm going to blog about some of the difficulties and (hopefully) solutions I discover as I go through the process. One of the main problems with MERB is the lack of documentation so hopefully with these blog posts, I can help with that.
First up, HTTP authentication. In the merb.yml it says the following:
All well and good, but what if you want to validate the authentication against a database of users?
Well the answer is to overwrite the authenticated? method in BasicAuthenticationMixin
This is easy to do, in your application.rb, do something like this:
Note: You still have to uncomment the basic_auth configuration in merb.yml. But it doesn't matter what the username/password is there since you'll be overriding them anyways.
First up, HTTP authentication. In the merb.yml it says the following:
# If you want to protect some or all of your app with HTTP basic auth then
# uncomment the following and fill in your credentials you want it to use.
# You will then need to set a 'before' filter in a controller. For example:
# before :basic_authentication
#:basic_auth:
# :username: ezra
# :password: password
# :domain: localhost
All well and good, but what if you want to validate the authentication against a database of users?
Well the answer is to overwrite the authenticated? method in BasicAuthenticationMixin
This is easy to do, in your application.rb, do something like this:
class Application < Merb::Controller
before :basic_authentication
private
def authenticated?
# if you want get the username and password that was inputted via http use:
# username, password = *credentials
# then validate the user by authenticating against a datbase or whatever
# make sure the return value is true or false
end
end
Note: You still have to uncomment the basic_auth configuration in merb.yml. But it doesn't matter what the username/password is there since you'll be overriding them anyways.
Saturday, 3 February 2007
Using Rails with JRuby
In this post I'm going to discuss how to get a rails application running using JRuby. It's not actually not that difficult to just get it running. (The real difficulties arrive when you get to databases and other areas of rails that arent fully covered by JRuby) I'm only going to be launching the application using the WEBrick server at script/server. If you were putting this into production mode you would want to use one of the many many deployment solutions like using glassfish, tomcat and stuff like that. I'm not going to get into that stuff in this post. WEBrick is good enough for development work and as a first step.
If you don't already have JRuby installed, have a look at my previous post.
If you've just installed JRuby and stroll into a rails application and type
I then discovered that actually JRuby has its own gem system. You need to install rails as a JRuby gem.
Check out http://www.headius.com/jrubywiki/index.php/JRuby_on_Rails for more detail but basically you use
to install rails as a gem for JRuby. This should produce this (assuming you have JRUBY_HOME defined):
Now go into a rails app:
Woohoo!
Go http://localhost:3000/ in your browser and if its a brand new application you should see the "Welcome to Rails page"
WEBrick is OK, but what about Mongrel?
While Mongrel is mostly Ruby, but it also contains some C (for speed reasons). JRuby can't do anything with C so for now Mongrel is out (More about that here.). What is necessary is the conversion of the C components in Mongrel to Java but as far as I know no-one has done that yet.
If you don't already have JRuby installed, have a look at my previous post.
If you've just installed JRuby and stroll into a rails application and type
# jruby script/serverYou will get this error
Cannot find gem for Rails ~>1.2.1.0:This is what I did and I was stumped by it at first because I already had version 1.2.1 or rails installed on my system. What was wrong with JRuby? Why didn't it realise this?
Install the missing gem with 'gem install -v=1.2.1 rails', or
change environment.rb to define RAILS_GEM_VERSION with your desired version.
I then discovered that actually JRuby has its own gem system. You need to install rails as a JRuby gem.
Check out http://www.headius.com/jrubywiki/index.php/JRuby_on_Rails for more detail but basically you use
# $JRUBY_HOME/bin/gem install rails -y --no-ri --no-rdocto install rails as a gem for JRuby. This should produce this (assuming you have JRUBY_HOME defined):
Bulk updating Gem source index for: http://gems.rubyforge.orgGreat!
Successfully installed rails-1.2.1
Successfully installed rake-0.7.1
Successfully installed activesupport-1.4.0
Successfully installed activerecord-1.15.1
Successfully installed actionpack-1.13.1
Successfully installed actionmailer-1.3.1
Successfully installed actionwebservice-1.2.1
Now go into a rails app:
$ cd ~/webprojects/mygreatnewrailsapp.com
$ jruby script/server
=> Booting WEBrick...
=> Rails application started on http://0.0.0.0:3000
=> Ctrl-C to shutdown server; call with --help for options
[2007-02-03 13:48:03] INFO WEBrick 1.3.1
[2007-02-03 13:48:03] INFO ruby 1.8.5 (0) [java]
[2007-02-03 13:48:03] INFO WEBrick::HTTPServer#start: pid=29324282 port=3000
Woohoo!
Go http://localhost:3000/ in your browser and if its a brand new application you should see the "Welcome to Rails page"
WEBrick is OK, but what about Mongrel?
While Mongrel is mostly Ruby, but it also contains some C (for speed reasons). JRuby can't do anything with C so for now Mongrel is out (More about that here.). What is necessary is the conversion of the C components in Mongrel to Java but as far as I know no-one has done that yet.
Installing JRuby on Ubuntu
This post is going to detail the steps I had to take in installing JRuby on my Ubuntu system. Note: these steps would probably work just fine on most other Linux systems but I haven't tried it so I cant say for sure.
You will probably need to install all this as root.
Prerequisites
The first thing you need is Java. You need the Java JRE and JDK (at least version 1.4 according to this http://svn.codehaus.org/jruby/trunk/jruby/README). I'm not going to go through the details so Ill just point you towards some tutorials
https://jdk-distros.dev.java.net/ubuntu.html - the easy way
http://java.sun.com/javase/downloads/index.jsp - the less easy way
To verify you have Java, just check the version. You should get something like this:
If you have Subversion you can just go
Then:
Ok, great you've built JRuby but you can't run it from the commandline yet!
Add JRuby to the path
Duh-oh! You need to add jruby to your path. I'm going to assume you use Bash, but it should be similar enough for whatever shell you use.
Add this:
Now reload your bash profile
(Note to add JRUBY_HOME to the global path, add
http://www.troubleshooters.com/linux/prepostpath.htm )
Now try this:
Well thats about it. JRuby is now installed and you can use it as a ruby interpreter in the same way that you would use the official ruby interpreter.
You will probably need to install all this as root.
Prerequisites
The first thing you need is Java. You need the Java JRE and JDK (at least version 1.4 according to this http://svn.codehaus.org/jruby/trunk/jruby/README). I'm not going to go through the details so Ill just point you towards some tutorials
https://jdk-distros.dev.java.net/ubuntu.html - the easy way
http://java.sun.com/javase/downloads/index.jsp - the less easy way
To verify you have Java, just check the version. You should get something like this:
# java -versionNext thing to install is Ant, its a prerequisite for building JRuby.
java version "1.5.0_08"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_08-b03)
Java HotSpot(TM) Client VM (build 1.5.0_08-b03, mixed mode, sharing)
# apt-get install antVerify you have ant:
# ant -versionBuilding JRuby
Apache Ant version 1.6.5 compiled on July 5 2006
If you have Subversion you can just go
# svn co http://svn.codehaus.org/jruby/trunk/jrubyIf you dont have Subversion you can download it here: http://dist.codehaus.org/jruby/ and extract it using:
# tar -xzvf jruby-src-LATEST.VERSION.tar.gz(At this point it might be a good idea to move the jruby folder to somewhere like /usr/local/lib just to make it more globally available and less specific to any particular user. This location, where ever you decide, will be called JRUBY_HOME)
Then:
# cd ./jrubyYou should get output like this:
# ant clean jar
Buildfile: build.xmlIf you didn't get a Build Successful, you've got problems, loser! Woah, thats probably a bit harsh. But seriously, you're on your own.
init:
clean:
[delete] Deleting directory /usr/local/lib/jruby/build
[delete] Deleting 2 files from /usr/local/lib/jruby/lib
[delete] Deleting directory /usr/local/lib/jruby/docs/api
init:
prepare:
[mkdir] Created dir: /usr/local/lib/jruby/build
[mkdir] Created dir: /usr/local/lib/jruby/build/classes
[mkdir] Created dir: /usr/local/lib/jruby/build/classes/jruby
blahblahblabh java ant creation stuff filler text blahblahblah
jar-jruby:
[jar] Building jar: /usr/local/lib/jruby/lib/jruby.jar
jar-openssl:
[jar] Building jar: /usr/local/lib/jruby/lib/jruby-openssl.jar
jar:
BUILD SUCCESSFUL
Total time: 11 seconds
Ok, great you've built JRuby but you can't run it from the commandline yet!
Add JRuby to the path
# jruby
bash: jruby: command not found
Duh-oh! You need to add jruby to your path. I'm going to assume you use Bash, but it should be similar enough for whatever shell you use.
# vi ~your_username/.bashrc
Add this:
to the end of the file.
JRUBY_HOME=/usr/local/lib/jruby # or where ever you put it.
PATH=$PATH:$JRUBY_HOME/bin
Now reload your bash profile
# source ~yourusername/.bashrc
(Note to add JRUBY_HOME to the global path, add
JRUBY_HOME=/usr/local/lib/jruby # or where ever you put it.to /root/.profile and (/root/.bash_profile or /root/.bashrc)
PATH=$PATH:$JRUBY_HOME/bin
http://www.troubleshooters.com/linux/prepostpath.htm )
Now try this:
# jruby -vAs Millhouse says: Radical!
ruby 1.8.5 (0) [java]
Well thats about it. JRuby is now installed and you can use it as a ruby interpreter in the same way that you would use the official ruby interpreter.
# jirb
irb(main):002:0> puts "moo!"
moo!
=> nil
irb(main):003:0>
Thursday, 25 January 2007
Installing Subversion 1.4.3 from source on linux
This compiled version does NOT link into apache for webdav and is probably not suitable as an svn server, only as a client. For that you need apxs and configure with --with-apxs and blahblahblah...
Download subversion and the dependencies from tigris.org
Extract them from .tar.gz
Then run configure and make
I think --with-ssl is necessary if you want to use https
And done! To test you've got the right version:
Download subversion and the dependencies from tigris.org
wget http://subversion.tigris.org/downloads/subversion-1.4.3.tar.gz
wget http://subversion.tigris.org/downloads/subversion-deps-1.4.3.tar
Extract them from .tar.gz
tar -xzf subversion-1.4.3.tar.gz
tar -xzf subversion-deps-1.4.3.tar.gz
Then run configure and make
# ./configure --with-ssl
# make
# make install
I think --with-ssl is necessary if you want to use https
And done! To test you've got the right version:
# svn --version
svn, version 1.4.3 (r23084)
Subscribe to:
Posts (Atom)