Back to VIM for Ruby and Rails

I learned to use VIM at the university to administrate linux systems and to develop C++ apps. Then I moved to Java and I enjoyed using an IDE like Netbeans. When I started to play with Ruby and Rails I kept using Netbeans as my editor of choice as it plays very well with them.

As I was bored with “Up arrow key, End key, Enter key” instead of “O” to insert a new line above my cursor and I wanted to play again with this so old but still alive editor, I installed the plugins: rails.vim (just great), haml syntax highlight (I ♡ haml) and irblack color scheme (more Textmate like).

With rails.vim, you get just great shortcuts to browse your rails source file. Type :Rmodel your_model_name to edit your model source file — :Rcontroller, :Rview, :Rmigration, :Rjavascript, :Rstylesheet… work too! It also includes :A (jump to alternate file) and :R (jump to relative file) commands. :A switches between source code and corresponding spec file, :R jumps from model to migration file. The most amazing combo: :AV to open up the alternative file (your spec file usually) in a vertical split window.

I finish up with the two commands I learned to use and love.1) Type ma to “mark” your cursor position as ‘a’ then type 'a to get back to this position. 2) Use qa to record a macro in ‘a’, press q again to stop recording. Then @a to replay it. Using commands to jump to next word / end of line / next something character it can be much faster than making a substitution using regexp or so.

Ruby 1.9 Faster Than Ruby 1.8?

Today I ran the following script with Ruby 1.8 & Ruby 1.9 to compare their performances:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def bench
  start = Time.now
  1000000.times do
    yield
  end
  puts Time.now - start
end

puts "Test 1: do things"
bench {
  "yeho!12".next
  rand(100)
  i ||= 1
  i = i + 1
}

puts "Test 2: \"stuff\""
bench {
  "stuff"
}

puts "Test 3: 'stuff'"
bench {
  'stuff'
}

puts "Test 4: :stuff"
bench {
  :stuff
}

Ruby 1.9 performances are promising:

Test Ruby 1.8 (sec) Ruby 1.9 (sec) Perf Increase
Test 1: do things 1.76 0.54 324.40%
Test 2: “stuff” 0.76 0.21 364.53%
Test 3: ‘stuff’ 0.80 0.21 388.91%
Test 4: :stuff 0.70 0.13 525.98%

So Ruby 1.9 is 3 to 5 times faster than Ruby 1.8 to run simple operations. I then checked with a small Rails app.

Once I got rubygem installed for Ruby 1.9, the gems I needed installed for Ruby 1.9, the plug-ins I use patched for Ruby 1.9, and my ruby code patched for Ruby 1.9, – yes, it was painful! – I fired: time spec spec

Ruby 1.8

$> time spec spec
............................................

Finished in 0.594813 seconds

44 examples, 0 failures
spec spec  2.49s user 0.79s system 93% cpu 3.522 total

Ruby 1.9

$> time spec spec
............................................

Finished in 0.625589223 seconds

44 examples, 0 failures
spec spec  8.74s user 0.32s system 93% cpu 9.648 total

Grrrr. Ruby 1.8 & 1.9 both pass the specs in ~0.60 second but Ruby 1.9 takes 8.74 seconds in total vs 2.49 seconds for Ruby 1.8. The same behavior occurs when running a Webrick server via script/server: Ruby 1.9 is 2 times slower than Ruby 1.8 to boot up the server and it handles the requests just as fast as Ruby 1.8.

Any Ruby guru to explain such deceiving results?

How-to Fix Low Volume on Ubuntu (Dell Laptop: Intel Hda Soundcard)

It took me a while to find a way to fix it as all the alsa-mixers where set at 100%.

The solution: run alsamixer -D hw:0 to display a new mixer called “Front” set at 70% by default – shift it to 100% and you can now listen to music or watch a film at a comfortable level!

Ps: If anyone knows how to increase the internal mic input volume and/or make the front mic work on an Dell XPS M1530: I’m definitely interested!

Make Acts_as_versioned Create New Version on Demand

I use acts_as_versioned to manage versions of Rails models. As I don’t want to create a new version of my document everytime I save it (to fix a typo for instance), I added a virtual attribute called save_with_revision to my model and put it into the definition of version_condition_met?.

1
2
3
4
5
attr_accessor :save_with_revision

def version_condition_met?
  @save_with_revision.to_s[/true|1/] != nil
end

Cool… except that it does not save intermediate updates into the **_versions table. Let say you create document version 1.0, then update it without creating a new version (from v1.1 to v1.4) and finally save a new version (v2.0); v1 will still be v1.0 and not v1.4.

To save intermediate updates into the **_versions table, just add to your model:

1
2
3
4
5
def after_update
  if !version_condition_met? && changed?
    versions.find(:last).update_attributes(self.attributes)
  end
end

Hope it helps. :)

Anyone with a better solution?

File Versioning in Ruby on Rails With Paperclip & Acts_as_versioned

This short tutorial shows you how to manage file versioning in Ruby on Rails by making Paperclip falling in love with acts_as_versioned. Paperclip & acts_as_versioned are plug-ins for Ruby on Rails: Paperclip manages file upload, acts_as_versioned enables models versioning.

Patch Paperclip

I patched Paperclip to keep old files when a new revision is saved. A fork of Paperclip adding the option keep_old_files to make Paperclip working with acts_as_versioned is available here: http://github.com/pcreux/paperclip/tree/master. You can install it running:

script/plugin install pcreux_paperclip

Update your Paperclip + acts_as_versioned model

Just three things to do:

  1. update the url & path to store your files by ‘version’
  2. set the option keep_old_files to true when a new version get saved
  3. add the interpolation of :version
1
2
3
4
5
6
7
8
9
10
11
12
class Document < ActiveRecord::Base
  has_attached_file :attachment,
                    :url => "/system/attachments/:id/:version/:style/:basename.:extension",
                    :path => ":rails_root/public/system/attachments/:id/:version/:style/:basename.:extension",
                    :keep_old_files => :version_condition_met?

  acts_as_versioned

  Paperclip.interpolates :version do |attachement, style|
    attachement.instance.version.to_s
  end
end

I hope it helps. :)

Behavior Driven Development in a Nutshell

A good development practice is to use automated tests to ensure the application works well and to facilitate refactoring. It is even better to write these unit tests before writing the code: this practice is called Test Driven Development (TDD) and it is a great way to check that the code is what it is excepted to be. Behavior Driven Development (BDD) goes a step further as you write specifications describing what the code does.

Behavior Driven Development is more about interactions with the application than just unit testing. It forces the developer to understand the responsibility of the method he is about to write. Using good tools, the specs written to test the application can be used as specifications.

Ruby BDD frameworks

RSpec is famous ruby BDD framework that plays with contexts and assertions. It is mainly used to describe the behavior of application code in specific contexts.

1
2
3
4
5
6
7
8
9
10
11
describe Calculator do
  context "switched on" do
    before(:all) do
      @calc = Calculator.new.switch_on!
    end

    it "should have a result equal to 0" do
      @calc.result.should equal(0)
    end
  end
end

These specifications are a good documentation for developers as they focus on the application code. Since BDD encourages collaboration between developers & non-technical participants, we need a tool describing the application at a higher level: Cucumber, to the rescue!

Cucumber permits to describe how the application should behave via user stories written down in a business-readable language. A scenario looks like that:

1
2
3
4
Given I am on the messages page
When I fill in "Content" with "Hello"
And I press "Send"
Then I should see "Message sent!"

These plain-text scenarios can be shared between developers and non-technical participants to validate the application behavior. Each step of this scenario is defined in Ruby to permits to run the scenario against the application and to generate a detailed development-status report.

BDD process

The focus of BDD is the language and interactions used in the process of software development. It implies outside-in development starting with User Interface definition to code development. Therefor, you create scenarios for the features you would like to develop and then follow the BDD process:

BDD process schema

  1. for each scenario describing a feature
  2. run the scenario – it fails (go red)
  3. define the first step – go red
  4. write down the application code getting the step to pass – go green
  5. refactor the code and repeat steps 4 & 5 for each step until…
  6. the scenario passes – go green
  7. refactor the application code

Once your done, you can move on to the next feature. :)

These scenarios drive the developer into the development process. It forces him to focus on writing down the test or application code to get the current step to pass, before moving on to the next step. The developer is also gratified every time a step passes and he knows with precision which features work.

I use Behavior Driven Development to develop Ruby on Rails applications. I work with non-technical participants on Cucumber scenario and I can give easily generate a project development status that shows working / pending / not-working scenarios. When switching to “development mode”, I just focus on getting the next step to pass – my mind is free of thoughts concerning the feature definition & application requirements. I usually get a step to pass in a couple of minute and everytime it occurs, it am gratified of seeing it going green. Finally, the refactor process occuring everytime a step or a scenario pass, the application design is constantly evolving to fit just the requirements: that is emergent design.

Many developers I talked with say that it is hard to write tests before writing the code. I think it is just hard to switch to this method. Try it and the coding process will look easier and your code will get better – just because you will specify before coding instead of doing both at the same time. [BDD]: Behavior Driven Development [TDD]: Test Driven Development

Rubular — Regular Expressions Editing & Testing Made Easy

If you use to spend ages building and testing regular expressions, you might be interested in the online expression editor Rubular. Rubular is a handy way to test ruby-based regular expressions as you write them.

rubular

Since the regular expression flavor used in Ruby is “Perl Style”, you can use this tool to test regular expressions written for PHP (preg function), Python, Javascript etc. Enjoy!

Agile Development in a Nutshell

Waterfall project Cartoon - Generated from http://www.projectcartoon.com/

Funny isn’t it? But that is the way it goes in many companies developing software – especially in big companies and on big projects. This is the old school – but widely used – waterfall model. This software development process goes through the phases of Requirements, Design, Development, Testing & Maintenance one after the other. It relies on the dream that once a step is 100% complete, it is also 100% right and it drives us to the delivery of a working software even the one the customer wants. But it doesn’t go that way in the software industry: customers don’t know what they need and use to ask many useless features, project leaders don’t succeed to write down the perfect requirements, analysts spend ages building up software architectures writing down pages of diagrams – software is definitely one of the most complex artifact humans can build up – and developers are human too, so they make mistakes too.

The waterfall model is inspired by the industries, therefor by highly structured physical environments in which after-the-fact changes are prohibitively costly. We’re writing software and software are virtuals, right? So, you can change the whole architecture without any additional cost – except the time you spend updating the code. Enlarging an array is not as costly as enlarging a kitchen. Why do we use this development model then? Maybe because it is straightforward to build software like we would build an aircraft – or because people did not read correctly the article Winston W. Royce wrote in 1970 where it presents this model and said that it “is risky and invites failure”. :)

The solution: Agile methods!

It is easy and cheap to update software code. At least easier and cheaper than moving the kitchen upstairs. Therefor you can easily try & see. Try to implement a new feature and see if it 1) does work 2) is usefull. The rule of 80/20 applies very well in the software industry – for instance 80% of users use less than 20% of a software features. Since try & see looks like random programming I gonna present you some aspects of Agile development.

Many Agile development methods exist and they all follow the twelve principles of the Agile Manifesto. The four main values are:

  • Individuals and interactions over processes and tools

  • Working software over comprehensive documentation

  • Customer collaboration over contract negotiation

  • Responding to change over following a plan

Interactions, collaboration, embrace change… looks great isn’it?! But it’s easier to promote cool values than to follow them – and even harder to end up on a working software that suits user needs. To make it working, you have to follow an Agile method and work with people who want to follow it too.

Scrum — Get Agile!

Scrum) is an Agile development methods. It has been designed for management of software development projects but can be usedas a general project management approach.

Roles

Scrum defines three main roles in a Scrum team:

  • the Scrum Master, it maintains the process

  • the Product Owner, usually the customer ‑ it sets the directions of the software

  • the Team, it designs, develops, tests & deploys the software. The team is self-managed.

Scrum init

The scrum process is initialized with the creation of the product backlog. The product backlog can be seen as a wish list containing all the features the software should have. The Scrum team (including the Scrum master & the Product owner) is involved in the creation of the product backlog. The Product backlog is then reviewed and the features it contains are prioritized.

Three… Two… One… Ignition!

Once the product backlog is ready, the project is launched. The software development will be managed via small iterations from one to four weeks. At the end of each iteration, a new release of the software featuring new or updated features is deployed.

The following schema shows the iterative process:

Scrum_process

Each iterations (also called “sprint”) starts with the creation of a sprint backlog. The sprint backlog contains features coming from the product backlog which will be developed during the iteration. Everyday, a project status meeting called the Scrum occurs. The meeting is time-boxed to 15 minutes and everybody answers the three questions:

  • What have you done since yesterday?

  • What are you planning to do today?

  • Do you have any problem preventing you from accomplishing your goal?

At the end of each iteration, a new release of the software is deployed. The Product owner reviews this new release in order to validate it and to decide what the team has to developed or to refactor next.

The Scrum method does not describe the way developers code & test the application within a sprint allowing you to choose a method that suits your needs. The one I use is Behaviour Driven Development: it works as a charm with Scrum and it will be the topic of a future post.

I am Scrum master on a project involving four developers for the web agency O2Sources. We follow the Scrum method but we do not use every concepts and tools it offers like BurnDown chart#Burn_down) or Pig & Chicken roles#Roles). I didn’t talk about them in this post to keep it short and because I wanted to talk about concepts I know, I use and which works. Don’t hesitate to discover them by yourself – the wikipedia page of Scrum) could be a good start.

The project I am working on for O2Sources is called Townce. It is a Collaborative Working Web Application coded in Ruby on Rails. We follow the principles of Scrum &  Behavior Driven Development methods to manage its development. Thanks to the Agile method Scrum, we deploy new releases every one to two weeks. Every release is reviewed to adjust the design in oder to make it more intuitive, to develop only essential features and to refactor the code. To see our baby evolve one week after the other could not be possible without the use of great methods and tools like Scrum, Behavior Driven Development, Ruby on Rails, Cucumber, RSpec… but these are other topics.