markhneedham/blog huggingface dataset:
Ruby: Using alias with 'indexers'
Date: 2010-10-18 04:24:22

I've been browsing through some of the Rails routing code while following http://weblog.jamisbuck.org/2006/10/2/under-the-hood-rails-routing-dsl[Jamis' Buck's blog post] and I came across something I hadn't seen before while inside the 'NamedRouteCollection' class.

The bit of code which initially confused me is in RouteSet.add_named_route:

[source,ruby]
----

module ActionController
  module Routing
    class RouteSet
      def initialize
        ...
        self.named_routes = NamedRouteCollection.new
      end

      def add_named_route(name, path, options = {})
        # TODO - is options EVER used?
        name = options[:name_prefix] + name.to_s if options[:name_prefix]
        named_routes[name.to_sym] = add_route(path, options)
      end	
    end
  end
end
----

Reading the code on line 12 I was convinced that this code was being used to set a value into an array or hash so I was confused as to how the url/path helper methods which get added for named routes were being created since there didn't seem to be any code which was calling the method in 'NamedRouteCollection' which would create them.

I eventually stumbled into the initializer code above which made me realise that 'named_routes' wasn't actually a hash or array but an instance of 'NamedRouteCollection'.

The methods '[]=' and '[]' are aliases which call the 'add' and 'get' methods on 'NamedRouteCollection'

[source,ruby]
----

module ActionController
  module Routing
    class RouteSet
      class NamedRouteCollection
        def add(name, route)
          routes[name.to_sym] = route
          define_named_route_methods(name, route) # creates the helper methods
        end

        def get(name)
          routes[name.to_sym]
        end

        alias []=   add
        alias []    get
      end
    end
  end
end
----

For me it seems like perhaps the creation of the helper methods could be the responsibility of another object although I can see why it's been put in NamedRouteCollection since those helper methods are only created if you have a named route.

Either way it was pretty confusing for me initially that you could create this type of side effect from a method call that looked like it was just adding a key, value pair to an array.
Coding: Context independent code
Date: 2010-10-18 15:52:28

I've been flicking through http://www.growing-object-oriented-software.com/[Growing Object Oriented Software Guided By Tests] again and in Chapter 6 on Object Oriented Style I came across the part of the chapter which talks about writing context independent code which reminded me of some code I've worked on recently.

The authors suggest the following:

____
A system is easier to change if its objects are context-independent; that is, if each object has no built-in knowledge about the system in which it executes
____

I was writing a bit of code in our ApplicationHelper which would only be used in a certain context within one of the views.

The view code was roughly like this:

[source,ruby]
----

<% unless current_user.blank? %>
   <% if show_something_for(current_user) %>
      <!-- some html -->
   <% else %>
	 <!-- some other html -->
   <% end %>
<% end %>
----

with the 'show_something_for' method defined like so:

[source,ruby]
----

module ApplicationHelper
   def show_something_for(user)
      user.has_foo? and user.has_bar?
   end
end
----

Inside the 'show_something_for' method we're working off the assumption that user will not be nil based on that fact that it's being used inside a context where we've already checked that we do in fact have a user.

It's not identical to the situation the authors are describing but there is an implicit assumption in this method which would mean that we couldn't necessarily just go and use it anywhere else in the code base and assume that it'd work.

Having said that, the code is slightly simpler than if we had to assume that 'user' might be nil.

The situation in which we don't have 'current_user' happens when no user has logged in so the method warden mixes into our ApplicationController returns nil.

I think it would be possible to make use of the http://en.wikipedia.org/wiki/Null_Object_pattern[null object pattern] and store a guest user in the session but there are a fair few places in the code base that rely on the current implementation at the moment.
Ruby: Using a variable in a  regex
Date: 2010-10-27 13:55:27

We're using Web Mock on my current project to stub out some of the external web requests in some of our integration tests and I managed to get myself very confused while trying to use a variable inside a regular expression that I was trying to pass to the 'stub_request' method.

The code was roughly like this:

[source,ruby]
----

some_url = "http://service.com/method"

stub_request(:any, /some_url/).
        to_return(:body => File.new('/path/to/some.xml'),
                                      :headers => {'Content-Length' => 666, 'Content-Type' => 'text/xml'},
                  :status => 200,
                  :headers => {'Content-Type' => 'text/xml'})
----

The request was being stubbed when I hard coded the url inside the regular expression but not being stubbed when I used the variable like in the example above.

I somehow missed the blindingly obvious in hindsight solution of treating variables inside a regular expression as if they were being used in a string.

If we wrap the variable inside '#{}' then our problem is solved:

[source,ruby]
----

some_url = "http://service.com/method"

stub_request(:any, /#{some_url}/).
        to_return(:body => File.new('/path/to/some.xml'),
                                      :headers => {'Content-Length' => 666, 'Content-Type' => 'text/xml'},
                  :status => 200,
                  :headers => {'Content-Type' => 'text/xml'})
----

I still can't quite believe I didn't spot it straight away.
Ruby: Active Record - Using 'exclusive_scope' in IRB
Date: 2010-10-11 19:03:39

http://twitter.com/#!/ashwinraghav[Ashwin] and I have been working recently on a bit of code to make it possible to 'soft delete' some objects in our system.

We're doing this by creating an additional column in that table called 'deleted_at_date' which we populate if a record is 'deleted'.

As we wanted the rest of the application to ignore 'deleted' records we added a http://ryandaigle.com/articles/2008/11/18/what-s-new-in-edge-rails-default-scoping[default scope] to it:

[source,ruby]
----

class Foo < ActiveRecord::Base
   default_scope :conditions => "deleted_at_date is null"
end
----

This works fine but we wanted to be able to see the status of all the records in IRB and with the default scope 'Foo.all' no longer returns 'soft deleted' records.

Luckily Active Record provides a protected method called 'http://stackoverflow.com/questions/1648971/rails-why-is-withexclusivescope-protected-any-good-practice-on-how-to-use-it[with_exclusive_scope]' which we can use to get around this:

[source,ruby]
----

Foo.send(:with_exclusive_scope) { Foo.find(:all) }
----

Since it's a protected method we can only access it in IRB by using 'send' which is a bit hacky, something David Heinemeier Hansson would refer to as http://www.loudthinking.com/arc/2006_10.html[syntactic vinegar].

Interestingly our first attempt to use 'with_exclusive_scope' involved writing the above code like this...

[source,ruby]
----

Foo.send(:with_exclusive_scope) { find(:all) }
----

..which results in the following error because when the closure was created 'self' referred to the main object rather than to 'Foo':
[source,text]
----

NoMethodError: undefined method `find' for #<Object:0xb77cd94c>
    from (irb):62
    from /var/lib/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2143:in `with_scope'
    from /var/lib/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2151:in `with_exclusive_scope'
    from (irb):62:in `send'
    from (irb):62
    from :0
----

Since the main object has no method called 'find' we get an exception thrown.
Ruby: Getting Active Record validation errors twice
Date: 2010-10-29 04:27:41

I managed to create an interesting problem for myself while playing around with some code whereby I was ending up with validation errors appearing twice every time I called 'valid?' on a specific model.

I figured I was probably doing something stupid and in fact a few replies by Aaron Baldwin on http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/a848f697dd7eba61?pli=1[a mailing list thread on 'rubyonrails-talk'] helped explain exactly what I'd done:

____
Are you calling require 'employee' anywhere? If so you are likely causing the model to load twice which causes duplicate errors because the validates_presence_of method gets called twice.
____

I'd put the following code into a controller elsewhere somewhat unnecessarily since it didn't seem to be picking up the location of my model at the time:

code_submissions_controller.rb

[source,ruby]
----

require 'models/code_submission'

class CodeSubmissionsController < ApplicationController
  def new
    CodeSubmission.new
  end
end
----

http://ruby-doc.org/core/classes/Kernel.html#M005941[require] doesn't load a file if it's already been included but Aaron points out why it does on this occasion:

____
You are right that "require" will only load the file once. But if you load the class another way calling "require" will load it again.
____

As I understand it that controller code would also implicitly require 'code_submission' by the convention of inserting an underscore between the 'CodeSubmission' constant's names.

We therefore effectively have the following two requires:

[source,ruby]
----

require 'code_submission'
require 'models/code_submission'
----

Which explain how the file gets loaded twice and therefore why the validation method fires twice and therefore creates two errors!
Ruby: Hash default value
Date: 2010-10-16 14:02:37

I've been pairing a fair bit with http://twitter.com/#!/ashwinraghav[Ashwin] this week and one thing he showed me which I hadn't previously seen is the ability to http://ruby-doc.org/core/classes/Hash.html#M002853[set a default value for a hash] which gets returned if we search for a key that doesn't exist.

This is an idea that I originally came across while playing around with Clojure but with Clojure the default value was defined in the calling code rather than in the hash definition.

For example:

[source,lisp]
----

(def scores {:mark 10 :dave 20})

(get scores :tony :0)
----

For a similar piece of code in Ruby we could write the following:

[source,ruby]
----

scores = { :mark => 10, :dave => 20 }
scores.default = 0
----

Now if we search for a key that doesn't exist in the hash then we'll get the value 0:

[source,ruby]
----

scores[:some_other_guy]
0
----

We're using this in a couple of places in our code base already but it'll be particularly useful for an upcoming piece of functionality where we want to vary the look and feel of some pages depending on certain criteria.

For the majority of users the look and feel will remain the same but for some of them it will vary slightly. Controlling that behaviour by using a hash with some default settings therefore seems like a reasonably good fit.
Agile: The curse of meetings
Date: 2010-10-09 03:39:29

Something which can often happen with agile software development teams is that in the desire to take everyone's opinion into account for every decision *we end up having a lot of meetings*.

http://www.the-arm.com/2010/03/i-hate-meetings-they-make-me-sick/[Toni wrote about this a while ago] and described a situation where he'd managed to get rid of a meeting and just have a discussion after the stand up with the necessary people.

While this is a good idea I still think there are occasions where it's not necessary to discuss every problem down to the minute details with the whole team.

For example, this week we needed to make changes to some migration files to deal with the fact that we'd removed a gem which a migration previously relied on.

3 solutions were suggested and each had good and bad parts to it so any discussion amongst a group of people was likely to result in a split opinion on what the best approach to take was.

In that situation I think it makes much more sense for one pair to take the problem, work out what they think is the best solution and then *just do it*.

If it turns out that wasn't the best solution then we can change it in the future.

It can be quite difficult to persuade people that it's not necessary to have meetings because the meetings are usually are about things which affect the team so it seems to make sense to involve everyone.

On the other hand I like to think of *what people could be doing instead of attending that meeting*.

If what they could be doing would be more valuable then perhaps they shouldn't be in that meeting.
Distributed Agile: Context
Date: 2010-10-31 18:27:16

From my last couple of months working for ThoughtWorks in Pune I think the most common subject that I've heard discussed is how to ensure that the team offshore is receiving all the context about the decisions and direction being taken onshore.

What I've found most interesting is that I think out of all the teams that I've worked on in the last four years my current team has by far the most context about what the client wants to do and the approaches they want to take over the next few months.

I think the main danger of trying to provide this level of context is that it almost inevitably leads to over communication.

Three of my colleagues from Pune recently went to Chicago for a few weeks and having returned to Pune want to share the context they got in Chicago with us.

I'm a fan of *pulling information when you actually need it* so my preferred approach was to discuss each of the functional areas closer to the time that we'd actually be working on it rather than having the guys effectively do a brain dump on everything they've learnt right now.

My reasoning is that I find that I struggle the most to learn when someone gives me a whole load of information which I can't really connect to anything - i.e. *information out of context*.

http://www.learninggeneralist.com/2010/08/thoughtworks-university-story-of-our.html[The new design of ThoughtWorks University] provides an example of how learning in context can be very effective.

Interestingly I was significantly outnumbered by my colleagues when we voted on which approach to take. They preferred to receive the context up front rather than later on.

I decided to go to a few of the sessions anyway and while the context has been well presented, I am finding that I forget the specifics of those sessions pretty quickly since I don't have anything to link the concepts to nor am I using the information I've learnt right now.

I've also noticed less and less people attending these sessions for similar reasons.

My opinion on this type of thing is that as long as I know where I can get the data from when I need it then that's enough. I don't need to have all the details up front.

I'm not sure if this observation has anything to do with the team being offshore, if it's a cultural thing or none of the above.

It'd be interesting to hear about others' experiences.
Meetings: Guerilla Collaboration
Date: 2010-10-31 14:53:40

As I've mentioned on twitter a few times my current team has a lot of meetings and apart from using the passive aggressive approach that http://tobytripp.github.com/meeting-ticker/[Toby Tripp's meeting ticker] provides I've also been flicking through Chapter 19, 'Guerilla Collaboration', of Jean Tabaka's 'http://www.amazon.com/Collaboration-Explained-Facilitation-Software-Project/dp/0321268776/ref=sr_1_1?ie=UTF8&s=books&qid=1288536162&sr=8-1[Collaboration Explained: Facilitation skills for software project leaders]' which gives other ideas.

I've also seen some useful ideas that my colleagues have used in meetings that I've been part of.

== Agenda/Purpose of the meeting

Jean suggests that we ask the meeting organiser for an agenda in order to ensure that:

* We aren't wasting the time of some participants
* We aren't missing any important attendees
* The meeting has a focus and people aren't at a loss for what to do

I've noticed the 1st and 3rd of these happening more frequently and it's typically because the topic of the meeting is very generic which means that anything goes!

== Time Check

Calling for a time check is useful for helping ensure that the time in the meeting is being used effectively and that the meeting doesn't over run the allocated time.

Having a start and end time for the meeting is also useful because otherwise a meeting can drift on for hours without any conclusion.

Creating a constraint - of time in this case - helps to keep things a bit more focused and http://www.markhneedham.com/blog/2010/08/16/creativity-john-cleese/[in theory could lead to move creativity].

== Keeping the discussion on track

This is typically easier for the meeting facilitator to do but it's certainly possible for an attendee to ask whether a certain discussion is relevant or if it can be taken offline.

I find that discussions can often drift into implementation detail i.e. the http://www.markhneedham.com/blog/2010/10/25/communication-logging-levels/[wrong logging level] and http://www.markhneedham.com/blog/2010/10/09/agile-the-curse-of-meetings/[totally isolate the majority of the meeting's participants].

It's certainly important to be careful when doing this because you might be wrong about what 'on track' means and people can quickly stop contributing if you consistently shut them down.

== Parking lot

This would typically just be a section of the whiteboard used to 'park' discussions about topics which we can get to later but aren't part of the purpose of the meeting.

I haven't seen this used that often but it seems like a useful technique because it still acknowledges that someone has a valid point, just that it's not for discussion at the moment.
Ruby: Getting the caller method with Kernel.caller
Date: 2010-10-08 13:19:56

One of the things I've been finding when debugging Cucumber specs is that due to the number of levels of indirection present in those examples it becomes quite difficult to work out exactly how certain pieces of code got called.

In one cuke we were trying to work out how 4 objects of the same type were ending up in the database when it seemed like there should only be two.

Having failed to figure it out just by reading the code we resorted to putting calls to http://ruby-doc.org/core/classes/Kernel.html#M005929[Kernel.caller] inside the http://github.com/thoughtbot/factory_girl[Factory Girl] setup code so we could see how we'd ended up at that code:

[source,ruby]
----

p caller.inspect
----

It's not a perfect solution - since the scenarios we write get parsed by Cucumber it's hard to tell exactly which line the call stack started on - but it provided enough information for us to track down the steps which were calling the Factory Girl code in question.
Ruby: Mocking or stubbing methods on the system under test
Date: 2010-10-24 17:30:26

An approach to testing which I haven't seen before and am therefore assuming is more specific to Ruby is the idea of stubbing or mocking out functions on the system under test.

I've come across a couple of situations where this seems to be done:

. When stubbing out calls to methods which are being mixed into the class via a module
. When stubbing out calls to private methods within the class

I think the first approach is fine because typically we'll have a direct test against that module's methods elsewhere and it doesn't make much sense to test the same thing again.

I initially liked the second approach as well because it simplifies the spec we're writing.

For example if we have this code:

[source,ruby]
----

class FoosController : ApplicationController
   def index
      populate_something
   end

   private

   def populate_something
      @something = Something.find(...)
   end
end
----

Then by stubbing out 'populate_something' we can write a spec like this:

[source,ruby]
----

describe FoosController do
   it "should populate something" do
      controller.stub(:populate_something) # and so on

      get :index
   end
end
----

Rather than:

[source,ruby]
----

describe FoosController do
   it "should populate something" do
      Something.stub(:find) # and so on

      get :index
   end
end
----

This is a fairly contrived example of course and the temptation to stub out a method on the system under test increases as the amount of dependencies and the complexity of them increases.

The problem we create for ourselves is that if we want to change the internal structure of our class, perhaps by inlining those private methods, then we'll end up with specs failing even if the external behaviour remains exactly the same.

My current thinking is that if we get in a situation where we want to stub out something on the system under test then it'd probably be better to listen to that pain and try and work out a cleaner way of solving the problem.
Agile: Constraints
Date: 2010-10-13 14:03:54

I recently came across quite an interesting post written by Steve Garnett where he discusses http://businessagile.blogspot.com/2010/09/constraining-agility.html[the difference between constraints and impediments inside organisations].

He comes to the following conclusion:

____
For me, the difference between an impediment and a constraint is whether the individual, team, organisation, enterprise, or industry considers the obstacle as removable. If whoever is working with the obstacle believes *it can be removed then it is considered an impediment*, if the same person *doesn't not believe it can be removed, or doesn't wish to work towards it's removal, it's considered a constraint*.
____

Over the last few years of working in various different organisations my experience is that there will always be some sort of obstacles and while I think Steve's distinction is useful, it's also helpful to consider whether we want to commit our time and energy to removing particular obstacles.

My former colleague http://dan.bodar.com/[Dan Bodart] referred to this as '*choosing your battles*' and as well as saving energy and enthusiasm by choosing to live with some obstacles it also has the benefit that people who can help us remove obstacles will be more receptive to us if we're selective in the battles we choose to fight.

The other thing that I've noticed is that people in the same team have different opinions on what they consider a constraint or impediment.

For example, I wrote last year about http://www.markhneedham.com/blog/2009/10/21/the-effect-of-adding-new-people-to-project-teams/[the benefit we can get from introducing new people with fresh perspective into a situation].

I found it interesting to notice the different perspectives of the new people compared to those of people who had been there a while.

Quite frequently something which the people who'd been there a while would consider to be a constraint would be seen as an impediment by the newer guys.

Another thing that we learnt from this situation is that sometimes waiting for a while can be a useful tactic before trying to remove an obstacle.

By this time we'll have hopefully built a bit more credibility and trust within the system that we're trying to change.