Friday, 9 April 2010

Invention is not invented here

In keeping with the subject matter, I want to rip off my own Go FUBUMVC yourself post by rehashing the idea and writing about it again.

It is a blatant rip off of the last post.  It is lazy and requires little thought.  I could write about something new but why bother when this is guaranteed to get some traction.

Now on with the show.........

Not a week goes by without my RSS reader mentioning a new .NET OSS project that is a complete rip off of an existing project.

The latest one to sadden my eye is the AutoPoco project by Rob Ashton.  We already have NBuilder and AutoFixture so what on earth do we need another one of these for?  

It then turns out that Karl Seguin or whatever his name is states that he wants to write another validation framework.  Are you absolutely mad? Another one?  We already have 3,089,298 validation frameworks muddying the waters and taking the word diversity to new levels.   What do you really hope to achieve by writing another validation framework?  Maybe we can really abuse lamdas into a totally ridiculous syntax.  Why not put a fluent interface on top of a fluent interface.

I think what saddens me the most is how many man hours are required for the new project to get into a state of parity with the existing project that is being ripped off.  

We will never compete with platforms like Ruby on Rails without invention or innovation.

There are of course some less time consuming acts that you can choose rather than a total rewrite of an existing system:

  1. Get involved with the existing project you are about to rip off.  This will never happen as the developer wants his name on the door.
  2. Fork the code of the existing project and save yourself the hassle of having to write all this crap from the start.
  3. Write another IoC container. 

I am further saddened by the fact that the developers in question are probably quite talented and could put this time to the betterment of the .NET ecosystem.

My theories as to the why of all this blatant plagiarism are this:

it is time consuming to find a worthwhile problem to solve.  

This time could be spent writing code.  Finding a good problem means placing your brain in unfamiliar places.  I know myself how difficult this is after spending two months coming up with a MicroIsv product idea to pursue.  My urge to go down the familiar routes of project management and CRM was strong but I stuck with it and eventually came up with a product I was able to in some ways convince myself has potential and has a market with some good and testable market research.  

I just want to write code

As developers we want to write code, we do not want to create mindmaps or brainstorm through a list of possibilities before going through the whole process again to define the problem space.  I could easily pop out a mocking framework or a .NET build engine in the same time with less effort.

I might fail

I know about failure on this front more than most as in a lot of ways horn has been a failure.  It is certainly a failure in the community I tried to build around it and it still has some failings in the technical solution.  I can though say I tried.  I can also say that my mind was placed in some very unfamiliar and unusual places as I thought about the problem.  With a pre-defined problem space like AutoPoco is ripping off, what do I learn on a non-coding basis.  Free your mind and your ass will follow.

Why not pick an existing problem and rewrite it?  I can change it slightly to my needs and if all else fails, I can always look at the source of the existing problem.

I will now court ultimate controversy and hatred from the .NET community by stating that one of its favourite son's is the ultimate plagiarist.

I speak of course of Ayende, before I list his list of similar projects, I do want to say that the guy has done amazing things for the community and at one point I looked forward to his blog posts with glee.  He has done more than most which is why I find it frustrating that he has not used his talent for more innovative ends.

Did we need another MSMQ with Rhino Queues?
Do we need another document database?
Do we need another memcached clone?
etc., etc.

The answer to all the above is no and I would say his most innovative project to date is NHProf which is ironically commercial.

I expect any Ayende sycophants reading this who take crawling to their master to new and sickening levels to proclaim a jihad against me.

Come and have a go if you think you are hard enough!!!!






















Thursday, 8 April 2010

Rails - Day 17 - Update and Delete

Rails  - Day 1 - The RubyGem Love Story
Rails -  Day 10 - Testing Rails Controllers
Rails -  Day 13 -ActiveRecord Relationships Part II
Rails - Day 15 - Rails Forms Part II

In the last post, we covered off validation.

We have been using a mock application of an expense tracker to illustrate the key points.  The expense records the expenses incurred running a small business.

In this post we want to finish the application off by completing our pseudo application by allowing updates and deletes of existing records.

Below is the index page of our expenses application that will allow a user to edit and delete existing expenses that we can create with our code thus far:


The edit action is analogous to the new action in that it just transfers control to a web page that will allow us to alter the details of an existing Expense model object.

As we mentioned in this post, the edit url takes the form of /expenses/123/edit.

Below is the haml created for each row in the above table:



This generates the following url:


At the moment, the haml that renders the screen below is all contained in the new.html.haml:



We want to abstract the Expense model rendering from the new.html.haml in order to reuse it from the edit.html.haml which is the template the rails runtime will look for by convention whenever a url similar to the one below is called:

/expenses/124/edit

The rails runtime will predictably look for a template named edit.html.haml by convention.

We extract the formbuilder haml and place it in a partial named _form.html.haml and update the new.html.haml to render from the partial:

The :locals => {:f => f} expression passes the formbuilder instance to the partial.

We can now easily create an edit.html.haml that will incorporate the partial:


Next we want to create an edit action in our ExpenseController that will retrieve the @expense instance from the database:


The @expense_types instance variable will contain a collection of all the ExpenseType objects that are mapped from records in the expense_types table.

With these sparse lines of code in place, we can now display an expense model that is ready for editing when we click on the edit link of one of the expense records that are displayed on the index page.

Rails routes several restful actions onto every resource that is generated by adding an entry similar to, map.resources :expenses to the routes.rb file.

The update action is the correct and obvious choice for updating our model.

The intricacies of setting up the relationships between the objects was done in the last post when we used accepts_nested_attributes_for to enable the complex Expense object to be created from the form fields submitted from the above page.

Below is the simple update action in our ExpenseController that will take care of the update or redirect to the edit and



In the above action, we are loading the expense object into memory and then calling the update_attributes method which updates all the attributes of a model from the passed in hash.  If the object is invalid, the saving fill fail and false will be returned.

In the event of a successful call to update_attributes, the user will be redirected to the index page where a confirmation message will be displayed which has been placed in the flash provider.


Deleting a Model

This is probably the simplest action to complete.  The delete link takes the form of the bin icon in the screenshot below.


This link is rendered from the following HAML:

=link_to "",  {:action => "destroy", :id => e.id}, :method => :delete, :class => "icon-delete", :confirm => "Are you sure"

This will render an anchor tag that links to a controller action called destroy and passing in the id of the expense we want to delete.  You can also see that the javascript confirm mechanism can be hooked up with the :confirm => "Are you sure" expression.

Below is the HTML that is rendered from the HAML:

<a href="/expenses/17" class="icon-delete" onclick="if (confirm('Are you sure')) { var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); m.setAttribute('value', 'delete'); f.appendChild(m);var s = document.createElement('input'); s.setAttribute('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', 'rW75EzBpl9r103D8zdIzX18upwh1Vs5dyp9RWYhJ31E='); f.appendChild(s);f.submit(); };return false;"></a>

The above link generates a lot of javascript which constructs a form and posts it to the server that will in turn be routed to the destroy action of the ExpensesController

This will call the following action in the ExpensesController:

 We simply retrieve the expense instance and call the destroy method.  We then place the confirmation message in the flash provider and redirect to the index page:

This ends my introduction to rails series. 

You can download the code that I created writing these posts from github here.







Tuesday, 6 April 2010

Rails - Day 16 - Validation

Rails  - Day 1 - The RubyGem Love Story
Rails -  Day 10 - Testing Rails Controllers
Rails -  Day 13 -ActiveRecord Relationships Part II
Rails - Day 15 - Rails Forms Part II
In the last post, we took a deeper look into working with a complex object and the Rails form builder.

We have been using a mock application example of an expense tracker to illustrate the key points.  The expense tracker will record the expenses incurred running a small business.

The complex object in question is an Expense model object that is made up of the following structure:


Below is the form we have constructed to capture an expense structure that is created from the inputs submitted in this form:



One thing that has not been mentioned so far is how to validate the user supplied input that is sent from this form to the server.  In this post we want to ensure that:

  • The External reference input has a value.
  • The posting Description input has a value
  • The user has selected an Expense Type from the dropdown
  • The net field has a valid monetary value added.  The net field is an attribute of the Expense's child object ExpensePayment.

If we take our first requirement from the above, we can create the following unit test to ensure our assertions:


Notice that there is also a test to check that the expense object is valid.  It is important to start from a good position and then assert failures.

In the above test, we are creating a valid @expense object and then setting the field we want to test (external_reference) to nil.

This test obviously fails as no validation instructions have been added on the Expense model.  

Rails Model Validators

When developing a Ruby on Rails application it is a good idea to use ActiveRecord validators to ensure the state of a model before trying a persist it to the database.  This type of validation is also known as first pass validation.

The most common approach is to use the declarative validates_xxxx_of class methods.

In order to make the above test pass, we use the validates_presence_of ActiveRecord class method to ensure an expense has an expense_payment attribute:


Our test now passes.  The validates_presence_of method takes a list of attribute names that we want to ensure have non nil values.  

Other similar attributes are:


We can validate the other attributes that we want to ensure are required like this:

validates_presence_of :external_reference, :description, :expense_date

But what about associated objects?  How can we verify that the user has selected an ExpenseType from the dropdown.  In our model, an Expense belongs to an ExpenseType.

In order to test this, we create the following test:



This type of relationship is very easy to validate.

The above test obviously fails but if we update the model to add the expense_type_id to the list of symbols passed as arguments to the validates_presence_of then all is good.

Our final two requirements concern the has_one  ExpensePayment relationship.  There are two things we need to test:

  • We need to ensure that there is an ExpensePayment child object contained within the Expense object.
  • We need to ensure that the contained child ExpensePayment  object has a non nil name field.

As ever we create the following failing tests:


In order to make the first test pass which ensures that an expense_payment object is contained with in the Expense model, we just update the symbol list validates_presence_of to include the :expense_payment attribute


This will enable our first assertion to pass but the second assertion still fails.

The first step is to add a call to validates_presence_of class method in the ExpensePayment object and include the net attribute.

We then update the  Expense object to include a call to the ActiveRecord validation class method validates_associated.


Above we can see the call to validates_associated :expense_payment which will instruct the framework to include the child object validations of the ExpensePayment model in the @expense.errors array.

With our validation tested, we now need to add the following to our new.html.haml view that will take care of displaying any validation errors:

And that is it, the error_messages_for :expense expression will display any error messages contained within the @expenses.errors array.

Below is how these error messages are displayed on the page.  Obviously you would style the div containing the error messages but as this is post 16, I simply cannot be bothered:


Obviously, this type of validation is very simplistic.  There are many hooks to get into this validation process for more complex scenarios. There are callbacks available on :before_save or :after_save or you can even override the validate_on_create or validate_on_update class methods.

In this post, we have discussed validation at a very high level.

In the next post, we will finish off the series by completing the update and delete actions.