markhneedham/blog huggingface dataset:
Rails: Populating a dropdown list using 'form_for'
Date: 2010-08-31 01:22:14

Last week we were trying to make use of http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html[Rails' 'form_for' helper] to populate a dropdown list with the values of a collection that we'd set to an instance variable in our controller.

My colleague pointed out that we'd need to use 'http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select[collection_select]' in order to do this.

We want to put the values in the 'foos' collection onto the page. 'foos' is a hash which defines some display values and their corresponding values like so:

[source,ruby]
----

class FooController < ActionController::Base
	def index
		# @mainFoo defined with some value irrelevant to this example
		@foos = { "value1" => 1, "value2" => 2 }
	end
end
----

The code we need to do this looks like this:

[source,text]
----

<%form_for @mainFoo, :html => { :name=> "ourForm", :id=> "ourForm" },:url => {:controller => "foo", :action => :bar} do | mainFoo |%>

<%= foo.collection_select :foo_id, {"Please select"=>""}.merge!(@foos), :last, :first, { :selected => "Please select" }, {:name => "foo", :id => "foo"} %>
----

The method signature that we're passing those parameters to reads like this:

[source,ruby]
----

def collection_select(method, collection, value_method, text_method, options = {}, html_options = {})
----

In this case we want the selected value to always be 'Please select' so we need to specify that in the 'options' hash. If 'selected' wasn't specified in the hash then the code would try to make the selected value @mainFoo.foo_id which in this case has no value anyway.

The other thing which I thought was quite neat is the way that you need to provided the 'value_method' and 'text_method' as parameters so that the dropdown list can be constructed with the appropriate labels and values.

In this case we have the display values as the keys in the hash and the values as the values in the hash so we can retrieve those entries from the collection by using the ':last' and ':first' methods.

We end up in the following method:

[source,ruby]
----

      def options_from_collection_for_select(collection, value_method, text_method, selected = nil)
        options = collection.map do |element|
          [element.send(text_method), element.send(value_method)]
        end
----

This creates an array of arrays which is used later on.

In our case the values passing through this method would read like this:

[source,ruby]
----

        collection = { "value1" => 1, "value2" => 2 }
		
        options = collection.map do |element|
          [element.send(text_method), element.send(value_method)]
        end
----

[source,text]
----

 => [["value1", 1], ["value2", 2]]
----

I was initially a bit confused about how we were able to call the 'collection_select' method on 'mainFoo' but http://github.com/rails/rails/blob/master/actionpack/lib/action_view/helpers/form_helper.rb[a quick browse of the ActionPack code] showed that 'mainFoo' actually represents a wrapper around that object rather than the object itself.
Objective C: Observations
Date: 2010-08-31 18:27:10

I've been playing around with Objective C over the last month or so and  although my knowledge of the language is still very much limited I thought it'd be interesting to describe some of the things about the language that I think are quite interesting and others that keep catching me out.

== Protocols

I touched on protocols a bit in http://www.markhneedham.com/blog/2010/08/04/objective-c-parsing-an-xml-file/[my first post] but they seem like an interesting middle ground between interfaces and duck typing.

I like the fact that protocols can define optional methods so that if we're not interested in some parts of the protocol we can just ignore those parts.

From the http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProtocols.html#//apple_ref/doc/uid/TP30001163-CH15[documentation page]:

____
Protocols free method declarations from dependency on the class hierarchy, so they can be used in ways that classes and categories cannot. Protocols list methods that are (or may be) implemented somewhere, but the identity of the class that implements them is not of interest. What is of interest is whether or not a particular class conforms to the protocol
____

== Smalltalkish style method names

We http://www.markhneedham.com/blog/2009/05/21/coding-dojo-15-smalltalk/[played with Smalltalk in a coding dojo a bit last year] and the first thing that I noticed with Objective C is that the method names are very similar to those in Smalltalk.

I think this influences the way that we define the method name and its parameters as you try and define those in such a way that when you call the method it will read better.

For example I created the following method:

[source,objc]
----

UILabel *aLabel	= [self createLabelFrom:project withXCoordinate:x withYCoordinate:y];
----

If I didn't have to name the parameters when calling the method I doubt I would have used such descriptive names. I would have just used 'x' and 'y' as the names!

== All methods are public/Defining methods in header files

As I understand it all the methods defined on an object are available to any other object to call i.e. all the methods are public

I've read about others using http://developer.apple.com/iphone/library/documentation/cocoa/conceptual/objectivec/Articles/ocCategories.html[categories] to simulate the idea of having non public methods but I haven't tried anything myself yet.

Interestingly we get a compiler warning when trying to call methods on an object if those methods haven't been defined in the appropriate header file although the code still seems to execute fine at run time.

== Messages not method calls

One other thing that I sometimes forget is that we're dealing with messages rather than method calls.

We still need to send the message to 'self' even if it's a message being sent to another method on the same object.
Objective C: Back to being a novice
Date: 2010-08-06 03:59:20

As I mentioned in my previous post about http://www.markhneedham.com/blog/2010/08/04/objective-c-parsing-an-xml-file/[parsing an XML file in Objective C] I'm a novice on the http://www.markhneedham.com/blog/2009/08/10/dreyfus-model-more-thoughts/[Dreyfus Model] when it comes to this type of development and I've found it interesting that I've dropped back into habits from my PHP days when I was first learning how to program.

== The big picture

My first instinct after I'd created a project in XCode was to try and understand how an iPad application fits together.

While this approach has worked fairly well for me in languages that I'm familiar with I found that I ended up shaving multiple yaks all at once.

I know too little about all of the individual components such that when I start reading how they all work together I end up veering off track and reading about how each of the components work on their own.

For the moment I've put the big picture to one side and I'm just trying to understand the ins and outs of the language by hacking bits of code together.

== Copy/Paste/Change/Comment

Talking about hacking code, I've found myself copying and pasting example code that people have posted and then tweaking it bit by bit, re-running the code each time to check I haven't broken anything.

Eventually I'll need to learn how to write the code from scratch but at the moment I make way too many mistakes that the copy/paste approach gives me quicker feedback about how the language works.

When the code stops working I find myself commenting out code until I get it back into a working state because I'm not yet able to intuitively narrow in on where the problem might be.

== Limit the hours a day

Perhaps due to the frustration of everything being a struggle I find that I'm quite mentally fatigued after coding for a few hours.

On the days when things work more frequently than not I find that I can code for longer but at the moment I'm finding it more beneficial to stop coding when I'm getting too frustrated and then pick it up later.

Quite frequently I'll work out how to do something that I was really struggling with after leaving it for a while.

== TDD\...

Despite being a big fan of Test Driven Development I haven't written a single test in Objective C yet.

While that will probably be the most effective way to develop code, as I've previously suggested, I don't necessarily think it's the most effective way to learn a new language.

The feedback loop is slowed down as you first try and setup a testing framework and because you don't know the syntax that well it'll probably be a bit of a struggle to get a test setup.

Writing a bit of code and then compiling and running it provides a feedback loop which is working fine for me at the moment although I'm sure at some stage I'll drift back towards my TDD roots.
Ruby: 'method_missing' and slightly misled by RubyMine
Date: 2010-08-23 21:07:46

Another library that we're using on my project is http://am.rubyonrails.org/[ActionMailer] and before reading through the documentation I was confused for quite a while with respect to how it actually worked.

We have something similar to the following piece of code...

[source,ruby]
----

Emailer.deliver_some_email
----

...which when you click its definition in RubyMine takes you to this class definition:
[source,ruby]
----

class Emailer < ActionMailer::Base
	def some_email
		recipients "some@email.com"
		from "some_other_email@whatever.com"
		# and so on
	end
end
----

I initially thought that method was called 'deliver_some_mail' but having realised that it wasn't I was led to the 'magic' that is 'method_missing' on 'ActionMailer::Base' which is defined as follows:

[source,ruby]
----

module ActionMailer
...
	class Base
		def method_missing(method_symbol, *parameters) #:nodoc:
        		if match = matches_dynamic_method?(method_symbol)
          		case match[1]
            			when 'create'  then new(match[2], *parameters).mail
            			when 'deliver' then new(match[2], *parameters).deliver!
            			when 'new'     then nil
            			else super
          		end
        		else
				super
        		end
		end
	end
end
----

The 'matches_dynamic_method?' function allows us to extract 'some_email' from the 'method_symbol'. That value is then passed into the object's initializer method and is eventually called executing all the code inside that method.

[source,ruby]
----

        def matches_dynamic_method?(method_name) #:nodoc:
          method_name = method_name.to_s
          /^(create|deliver)_([_a-z]\w*)/.match(method_name) || /^(new)$/.match(method_name)
        end
----

Reading through the documentation, the author gives the following reasons for having separate 'create' and 'deliver' methods:

[source,text]
----

ApplicationMailer.create_signed_up("david@loudthinking.com")  # => tmail object for testing
ApplicationMailer.deliver_signed_up("david@loudthinking.com") # sends the email
ApplicationMailer.new.signed_up("david@loudthinking.com")     # won't work!
----

In C# or Java I think we'd probably use another object to build up the message and then pass that to the 'Emailer' to deliver it so it's quite interesting that both these responsibilities are in the same class.

It also takes care of rendering templates and from what I can tell the trade off for having this much complexity in one class is that it makes it quite easy for the library's clients - we just have to extend 'ActionMailer::Base' and we have access to everything that we need.
One idea at a time
Date: 2010-08-12 18:59:54

One thing I noticed while pairing with some of the http://www.thoughtworks.com/thoughtworks-university[ThoughtWorks University] guys a few weeks ago is that I had an almost overwhelming urge to show them all sorts of coding techniques that I've learned, probably to the point where it'd be more confusing than helpful.

http://jkwerner2.wordpress.com/[JK] pointed out that it's more effective to bite your tongue and just focus on one idea at a time which is something that the authors of http://www.amazon.com/Agile-Coaching-Rachel-Davies/dp/1934356433/ref=sr_1_1?ie=UTF8&s=books&qid=1281621756&sr=8-1-spell[Agile Coaching] touch on briefly at the beginning of the book:

____
You're probably itching to get started, but where do you get started? There's no right place. The simplest approach is to pick one thing and jump in.
____

For example one story I joined involved adding a new feature which touched all layers of the application from the view through the service layer and to the database.

My favoured approach is to start from the UI and work out what we actually need to develop by starting from what the user will actually see i.e. outside in development.

The approach that had been taken on the story meant that the API of one of the services was being driven out straight from a service test rather than coming for a need for that method from the controller.

The reason I prefer to http://www.markhneedham.com/blog/2010/04/18/coding-another-outside-in-example/[drive out a story from the outside in] is that we don't have to try and imagine the way someone might want to use an object - we already know because we've written the consumer code for that method already.

While learning how to drive from the outside in is a useful skill, in this case the main skill that we were trying to encourage was test driven development and getting the grads used to the red - green - refactor cycle and so on.

Although it would have made our lives easier to stop and go and write the code for the controller which needed the service first, I think it would have been quite confusing to leave the service in a half completed state and move off to work on something else.

We therefore kept on working on the service code while trying to imagine exactly how it would be used by the controller.

While this wasn't the optimal way to develop this piece of code and perhaps took longer overall I think it was a more useful approach to take in this situation and is one I'd take again given similar circumstances.
Rules of thumb vs Exercise your judgement
Date: 2010-08-13 10:05:41

I spent a bit of time working through the first Micro Testing album of the https://elearning.industriallogic.com/[Industrial Logic eLearning suite] a few weeks ago and there's an interesting piece of advice towards the end of the album:

____
Microtesting is not a formula. It's a technique. When microtesting rigorously, you will be called constantly to make judgments like these, between one set of names and another, and their corresponding approaches. Remember the judgment premise. Don't let any technique or recommendation or rule of thumb become an excuse for not exercising your judgment.
____

While I think this is good advice I thought it was interesting that it seems to goes against http://www.markhneedham.com/blog/2009/10/04/coding-rules-of-thumb/[the rules of thumb] approach that I described in a blog post towards the end of last year.

It seems like Kerievksy and co are encouraging us to 'get out of the shu box', http://agilecoach.typepad.com/agile-coaching/2010/02/shuhari-considered-harmful.html?cid=6a00e54ee21bf288340120a893081c970b#comment-6a00e54ee21bf288340120a893081c970b[as Alistair Cockburn would put it], and into the reflective 'Ha' stage of the 'Shu Ha Ri' learning model.

* Shu, the student copies techniques without adapting them.
* Ha, the student reflects on what has been learned and breaks free from traditions.
* Ri, the student is now a practitioner extending the art.

I've previously written about my own learning style which seems to favour a http://www.markhneedham.com/blog/2010/02/26/shu-ha-ri-harmful/[strong adherence to practices without too much questioning] while I get used to them although I appreciate that others seem to reach the reflection stage quicker than I do.

Talking with a colleague about the value of pair programming he described one team he'd seen that had decided that it was an unnecessary practice to follow even though they hadn't spent very long using it.

As a result the team had become very siloed with each team member becoming an expert in one area of the code base, eventually leading to a situation where it was impossible to rotate anyone on the team.

From my experience we end up with the same situation if we try to make a judgement call on when and when not to follow a practice without having sufficient experience to work out how we might need to vary its use in different circumstances.

The last paragraph of Rachel Davies' post also points this out:

____
Learning new ways of working takes time. As Ron Jeffries once said "They're called practices for a reason".."You have to have done them. Practice makes perfect."
____

It's certainly useful to get into the habit of reflecting on what we're doing but I think we also need to be aware that we may not yet have the experience to make every judgement.
Objective C: Expected '(' before 'Project'
Date: 2010-08-14 10:33:24

A mistake I've made more than a few times while declaring headers in Objective C is forgetting to explicitly import the classes used in the interface definition.

I've been refactoring http://www.markhneedham.com/blog/2010/08/09/ipad-redrawing-the-screen/[some of the code I wrote earlier in the week] and wanted to create a 'LabelFactory'. I had the following code:

LabelFactory.h

[source,objc]
----

#import <UIKit/UIKit.h>

@interface LabelFactory : NSObject {
}

+ (UILabel*)createLabelFrom:(Project *)project withXCoordinate:(NSInteger)x withYCoordinate:(NSInteger)y;

@end
----

Which gives this error on compilation:

[source,text]
----

/Users/mneedham/SandBox/iPad/CIMon/LabelFactory.h:9:0 /Users/mneedham/SandBox/iPad/CIMon/LabelFactory.h:9: error: expected ')' before 'Project'
----

I've been wondering what that error message actually means for a while and more by accident than design I re-read the section of Apple's documentation on 'http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocDefiningClasses.html[referring to other classes]'

____
An interface file declares a class and, by importing its superclass, implicitly contains declarations for all inherited classes, from NSObject on down through its superclass. If the interface mentions classes not in this hierarchy, it must import them explicitly or declare them with the @class directive:
____

Declaring 'Project' with the '@class' directive just above '@interface' helps fix that problem:

[source,objc]
----

...
@class Project;

@interface LabelFactory : NSObject {

}
...
----

The original error message I was getting is still slightly mystifying to me...
Ruby: Accessing fields
Date: 2010-08-22 18:26:17

I've spent a little time browsing through some of the libraries used by my project and one thing which I noticed in http://as.rubyonrails.org/[ActiveSupport] is that fields don't seem to be accessed directly but rather are accessed through a method which effectively encapsulates them inside the object.

For example the following function is defined in 'inheritable_attributes.rb'

[source,ruby]
----

  def write_inheritable_attribute(key, value)
    if inheritable_attributes.equal?(EMPTY_INHERITABLE_ATTRIBUTES)
      @inheritable_attributes = {}
    end
    inheritable_attributes[key] = value
  end
----

[source,ruby]
----

  def inheritable_attributes
    @inheritable_attributes ||= EMPTY_INHERITABLE_ATTRIBUTES
  end
----

[source,ruby]
----

EMPTY_INHERITABLE_ATTRIBUTES = {}.freeze unless const_defined?(:EMPTY_INHERITABLE_ATTRIBUTES)
----

If we were using C# we'd have instantiated '@inheritable_attributes' at the field definition with 'EMPTY_INHERITABLE_ATTRIBUTES' like so...

[source,csharp]
----

public class SomeClass {
	private Dictionary<string, object> inheritableAttributes = new Dictionary<string, object>();
}
----

...but we can't do that in Ruby because we don't need to explicitly define all our fields, we just start using them.

I'm assuming this is quite a common pattern in Ruby and in a way it's quite neat because it restricts the number of direct field  references which will make it easier to change the underlying implementation.  http://www.markhneedham.com/blog/2010/07/05/the-limited-red-society-joshua-kerievsky/[Kerievsky's narrowed change refactoring] suddenly becomes less necessary!

For that reason I wonder whether it would be a useful pattern in C#/Java or if it would be overkill.
F#: Expressing intent and the forward/application operators
Date: 2010-01-04 11:11:10

A while ago I wrote about F#'s http://www.markhneedham.com/blog/2009/06/27/f-more-thoughts-on-the-forward-application-operators/[forward and application operators] where I'd looked at how these could be used to simplify code and while trying out http://osherove.com/tdd-kata-1/[Roy Osherove's TDD Kata] I realised that perhaps the choice of which of these to use or whether to use them at all depends on what intent we're expressing.

The specific bit of code I was writing was for raising an exception if negative values were provided and I originally thought I'd use the forward operator to express this code:

[source,ocaml]
----

    let digits = [| 1;2;3;-3 |]
    let buildExceptionMessage negatives = sprintf "No negative numbers allowed. You provided %s"
                                                  (String.Join(",", negatives |> Array.map (fun x -> x.ToString())))

    raise (ArgumentException (digits |> Array.filter (fun x -> x < 0) |> buildExceptionMessage))
----

I think in this case the forward operator doesn't actually express the intent of the code better because it puts the focus on the digits rather than on the building of the exception message.

I changed that a bit to emphasise the importance of the 'buildExceptionMessage' function:

[source,ocaml]
----

raise (ArgumentException (buildExceptionMessage (digits |> Array.filter (fun x -> x < 0))))
----

I thought it might be possible to get rid of the brackets around the filtering of the digits and instead apply that expression to 'buildExceptionMessage' using the application operator:

[source,ocaml]
----

raise (ArgumentException (buildExceptionMessage <| digits |> Array.filter (fun x -> x < 0)))
----

That actually results in the following error message:

[source,text]
----

Type mismatch. Expecting a  string -> string but given a  'a array -> 'a array. The type 'string' does not match the type ''a array'
----

The problem is that it applies digits to 'buildExceptionMessage' first and then tries to apply the result of that to Array.filter instead of applying the filter to the digits and then passing the result of that calculation to 'buildExceptionMessage'.

One way to get around this is to remove the forward operator and move digits to be the second argument passed to Array.filter instead:

[source,ocaml]
----

raise (ArgumentException (buildExceptionMessage <| Array.filter (fun x -> x < 0) digits))
----

This is the version that I've got at the moment and I think it expresses the intent of the code the best.

I'd be interested in hearing more thoughts on the best way to use or not use these operators in idiomatic F# code.