“...I've been working since 2008 with Ruby / Ruby on Rails, love a bit of Elixir / Phoenix and learning Rust. I also poke through other people's code and make PRs for OpenSource Ruby projects that sometimes make it. Currently working for InPay...”

Rob Lacey (contact@robl.me)
Senior Software Engineer, Brighton, UK

ActiveRecord joinery blah

Hmmzzz, this one doesn’t cope with nil user_ids

users = User.find(UsersUsbLesson.find(:all, 
                                      :select => "distinct user_id",
                                      :conditions => "user_id > 0"
                                      ).collect(&:user_id))

much better, and uses a join instead of two queries to the db.

users = UsersUsbLesson.find(:all, 
                            :select => 'distinct user_id, updated_at',
                            :include => 'user'
                            ).map(&:user).compact

Firefox has lost my favour

I am sad to say that I am follow the trend of slamming down Firefox. In recent months I’ve found that I am using it less and less. I was initially turned onto it because of the tab support and the frustration of having multiple IE windows open for multiple pages. It just feels more natural and now IE feels painful and not pretty enough, Firefox’s default style just adds more to the page I guess and feels nicer.

Then I looked at plugins and now I have a Operator (for detecting microformats), Firebug, Web Development Toolbar, Elasticfox (for managing Amazon EC2 instances), FireFTP. They are all extremely useful and things I use daily.

However, Firefox is just becoming slower and slower and I am having to restart it at least twice a day, whether I am on Windows or Ubuntu. I am swaying over to Google Chrome as its just slicker and altogether faster little beastie. I am now finding that I am using Firefox for editing css with the Web Developer Toolbar, and debugging javascript with Firebug and that’s it, so I’m not actually using as a web browser as such anymore. Sad times.

Passenger announce support for Nginx

While I am not a huge fan of Nginx, largely because I can install configure Apache in far less time with little or no messing around, its good to see that Nginx support is on its way. My current client uses Nginx, Mongrel and Monit to run their Rails app. I’ve always disliked the flakiness of the set up, in fact the set up was similar with former clients too. Its a common deployment scenario and Passenger just does all the hard work for you.

http://blog.phusion.nl/2009/04/16/phusions-one-year-anniversary-gift-phusion-passenger-220/

capturing the exit status of a system call

Nice little snippet I came across today. The next time I execute a script I can establish the result without having to parse the stdout or stderr.

>> %x{echo "Hello World"}
=> "Hello World\n"
>> $?
=> #<Process::Status: pid=949,exited(0)>
>> $?.exitstatus
=> 0
>> %x{ /etc/init.d/apache2 restart }
(13)Permission denied: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
Unable to open logs
=> " * Restarting web server apache2\n   ...fail!\n"
>> $?
=> #<Process::Status: pid=2016,exited(1)>
>> $?.exitstatus
=> 1

saving ActiveRecord objects without callbacks

Just found a broken test that I just couldn’t fathom, its testing an action that occurs within in an callback. We need to set up an object in the correct state to be inline without our live database. new_salted_password is set when the record is next saved, so it is important that it is nil before we call our method.

p = Thing.create(:user => 'robl', :password => '12345', :password_confirmation => '12345')
p.write_attribute(:new_salted_password, nil)

This has worked fine for sometime. Write attribute appears to skip callbacks. I could have written the following as the callback actually occurs within an after_validation callback and the validation step is skipped here.

p = Thing.create(:user => 'robl', :password => '12345', :password_confirmation => '12345')
p.new_salted_password = nil
p.save(false)

However, I needed to move the callback method within the before_save callback sequence so both of the above methods failed both save(false) and write_attribute saves the object. After much hunting it appears the solution is to the use the private method update_without_callbacks. There is also a create_without_callbacks method.

p = Thing.create(:user => 'robl', :password => '12345', :password_confirmation => '12345')
p.new_salted_password = nil
p.send(:update_without_callbacks)

OMG what's all this erlang malarky

Just picked up a copy of Programming Erlang from Pragmatic Programmers, and having a quick play in the console.

The story so far;

  • lines are terminated by ‘.’
  • variables are not variables (not quite) can only be assigned once
  • = is not an assignment operator, it is a pattern matching operator
rl@bloodandguts:~$ erl
Erlang (BEAM) emulator version 5.6.3 [source] [64-bit] [smp:2] [async-threads:0] [kernel-poll:false]

Eshell V5.6.3  (abort with ^G)
1> % This is a comment
1> 123456.
123456
2> "a string".
"a string"
3> 3 + 4 * 6.
27
4> (3 + 4) * 6.
42
5> 16#cafe .
51966
6> 32#cafe .
403950
7> X = 12345.
12345
8> X * 3.
37035
9> X = "something else".
** exception error: no match of right hand side value "something else"

testing ferret in the console with configuring models

Ok this doesn’t prove much, but if you use ActsAsFerret you can play with Ferret in the console to your heart’s content.

rl@bloodandguts:~$ ./script/console 
Loading development environment (Rails 2.2.2)
>> module Ferret::Analysis  
>>   class StemmingAnalyzer  
>>     def token_stream(field, text)  
>>      StemFilter.new(StandardTokenizer.new(text))  
>>     end  
>>   end  
>> end
=> nil
>> index = Ferret::I.new(:analyser => Ferret::Analysis::StemmingAnalyzer.new)
=> #<Ferret::Index::Index:0x7fc2683559f8 @open=true, @mon_owner=nil, @id_field=:id, @writer=nil, @searcher=nil, @mon_waiting_queue=[], @dir=#<Ferret::Store::RAMDirectory:0x7fc2683559a8>, @default_input_field=:id, @key=nil, @auto_flush=false, @mon_entering_queue=[], @qp=nil, @close_dir=true, @mon_count=0, @default_field=:*, @reader=nil, @options={:dir=>#<Ferret::Store::RAMDirectory:0x7fc2683559a8>, :analyzer=>#<Ferret::Analysis::StandardAnalyzer:0x7fc2683557f0>, :lock_retry_time=>2, :analyser=>#<Ferret::Analysis::StemmingAnalyzer:0x7fc268355a20>, :default_field=>:*}>
>> index << 'fly'
=> nil
>> index.search('fly').total_hits
=> 1
>> index.search('flies').total_hits
=> 0

Stubbing Time.now

There have been several times recently when I’ve needed to test that the time set in a particular method is Time.now. However, this isn’t particularly (or at all) accurate.

s = Story.new
s.access_it
s.last_accessed_at.should == Time.now

This all reads fine, but our test will always take time to run. So the current time when then the method is called is not likely to be same as the current time that it is being tested at and if it is then you are extremely lucky. Hence the following.

Time.stub!(:now).and_return(Time.now)
s = Story.new
s.access_it
s.last_accessed_at.should == Time.now

Links that are really POSTs

I’m really not a fan of using GETs to call actions that create things like so.

<%= link_to image_tag('mini_icons/copy.png', :alt => 'Make a copy of this lesson'), copy_lesson_path(lesson), :method => :post %>  <br/>
<%= link_to "Copy", copy_lesson_path(lesson), :method => :post %>

Despite using a form to pretend to be a link I much prefer this solution, because it actually enforces a POST to call the ‘copy’ action rather then pretending to be a post with a param { “_method” => “post” }

<% form_for lesson, :url => {:controller => '/lessons', :action => :copy, :id => lesson}, :html => { :method => :post, :class => 'button' } do |f| %>
  <label for="copy">
    <%= image_submit_tag('mini_icons/copy.gif', :alt => 'Copy Lesson', :id => 'copy') %>
    <span>Copy</span>
  </label>
<% end %>

errors with different rspec runtimes

Just tried re-running a spec before adding some new functionality and ….

can't activate rspec (= 1.1.12, runtime), already activated rspec-1.2.0 (Gem::Exception)

Ok so I decided to remove the bad version that was complaining.

sudo gem uninstall rspec -v 1.1.12

Gah, another error.

RubyGem version error: rspec(1.1.4 not = 1.1.12) (Gem::LoadError)

Ok so it must be something to do with version mismatches and there are always 2 gems required for RSpec with Rails. I guess rspec-rails looks for the nearest matched version of rspec

rl@bloodandguts:~$ gem list | grep "rspec"
rspec (1.2.0, 1.1.11, 1.1.9, 1.1.4)
rspec-rails (1.1.12, 1.1.11, 1.1.9)

A new install of rspec-rails actually then fixed everything up nicely.

rl@bloodandguts:~$ sudo gem install rspec-rails
Successfully installed rspec-1.2.2
Successfully installed rspec-rails-1.2.2
2 gems installed