Category Archives: Uncategorized

Date validation, display and parsing in Rails

 

 

When working with date formats and date validations in Rails, I have particular set of behaviours (spelling: a shout out to Peter Cooper)  I want to achieve. The code I’ve achieves this behaviour, but it seems to me it should be easier than this.

 

I include code so that 1) if you have been struggling to achieve these same behaviours, this code provides a solution, and 2) if you’re an old hand at Rails and I am writing more code than I need to, I would *really* appreciate any recommendations you can provide. Also, if any of this code is obnoxiously counter to “idiomatic Ruby/Rails”, meaning it works, but it’s “just not the Ruby/Rails way”, please let me know that as well.

 

Here is the behaviour I want in validating and formatting dates in Rails:

 

1) Validate that something has been entered.

2) I want to use the “chronic” gem because I love its ability to parse input such as “today” and “next Tuesday” and return the correct ruby Time object.

3) When editing an record (already has a valid date) and the user enters an invalid date value, or enters blank, I want the application to keep displaying the invalid value so they can see what they keyed and determine why they’re getting an error message. The default Rails behaviour is to redisplay the original, valid value.

4) Finally, I want the dates to be fetched from the database and displayed to the screen using the North American format of “mm/dd/YYYY”.

 

 

I created a micro application with one model, “Person” (table = “people”) and only three attributes:  first_name, last_name and date_of_birth.  In order to achieve all of the behaviour I listed above, I had to create a “virtual attribute” called “date_of_birth_display” which works with the view and use this field for shuttling date values back and forth between the view and the database as well as formatting purposes.  

 

 

Here’s the important part of the view code:

 

<table cellspacing=”0″>

<%= form_for(@person) do |f| %>

        #… Other fields omitted for brevity…

        <td><%= f.label :date_of_birth, “Date Of Birth” %></td>

        <td><%= f.text_field :date_of_birth_display %></td>

    </tr>

<% end %>

</table>

 

 

And now the model code:

 

require ‘chronic’

class Person < ActiveRecord::Base

  validate :date_of_birth_display_is_parseable? 

 

  def date_of_birth_display

    date_of_birth.strftime(“%m/%d/%Y”) unless date_of_birth.blank?

  end

 

  def date_of_birth_display=(val)

    @date_of_birth_display = val

  end

  

  def date_of_birth_display_is_parseable?

    self[:date_of_birth_display] = @date_of_birth_display

    

    if Chronic.parse(@date_of_birth_display)

      return self[:date_of_birth] =  Chronic.parse(@date_of_birth_display)

    end

    if @date_of_birth_display.blank?

       return !errors.add(:date_of_birth, “cannot be blank.”)

    else

      return !errors.add(:date_of_birth, “not a valid date.”)

    end

  end

end

 

Foundational Git feedback

I have just begun writing a book covering the open-source version control software called “git”.

The book is titled “Foundational Git” and can be read online, as I write it, at http://www.joemeirow.com/writing/books/foundationalgit/index.html. I am writing this post on 11/2/2011 and I have just basically started the book today.

Much about the book will change as I go along, but if you have any comments, please leave them here in the comments for this blog post. Thanks!

 

Joe Meirow

 

The best way to learn something…

While there are many positive aspects to working in a small development group, the downside is that we’re not exposed to many different points of view in the workplace. Unless we proactively seek outside influence through user-groups or actively monitor what’s new via the web, it is easy to unwittingly weave a cocoon around one’s self.

Over the past couple of months, I’ve been on a mission to sharpen my developer chops. Ours is a C#/.NET shop and so that was a logical place to start. After reading several blog-posts and articles expressing concern over the future direction of development in the Microsoft space, I began to get a bit nervous and for the first time thought about what development platform we should switch to, if it ever came to that.

For the time being, I am now relatively comfortable with the whole Windows 8/Metro thing, but during that unsettled time, I really began to thing about my life as a developer/architect in a completely different camp. One thing I knew for sure, Java was out.  I’d been there, done that long ago and have no desire to return. One of my co-workers is a huge Python fan and so I began to check out Python.

In the course of researching Python, it didn’t take long at all for Ruby to show up in many of the same web searches. And then, I was hooked.  I still haven’t written much more than a “Hello, World!” program in Ruby (been pretty busy with the C# stuff), but the Ruby language seems positively amazing and the  community absolutely electric. There is so much material available from the community that it’s almost overwhelming. I especially enjoy The Ruby Show with Jason Seifer and Peter Cooper. It is actually as entertaining as it is informative – a real “win/win”. Also extremely worthwhile is Ryan Bates’ excellent screencast series RailsCasts – Ruby on Rails Screencasts and Michael Hartl’s excellent, comprehensive Rail’s Tutorial.

The level of sophistication and the technologies in the web-client seem light-years ahead of the MS camp. (Disclosure: For those aspects of an organization that are externally-facing, of course web-applications are a must. For those that are exclusively internal, I much prefer a desktop app over a web app every day of the week and twice on Tuesday).

I’ve been listening to several Ruby podcasts during my commute over the past couple of weeks and it’s become abundantly clear that there is so much I have to learn. In fact, when I listen to the 37 Signals podcast, it’s almost if they’re speaking a different language. The slight amount of intimidation I feel about that is far outweighed by the thrill of learning all of this new stuff. I figure if I wrote assembler every day for four years, I can pretty much do anything.

They say there’s no better way to learn something that to learn it like you have to teach it. My plan is to write a series of “micro books” anywhere from 20-50 pages in length. Each will be part of an overall series and I think the series is going to be entitled “Bare Bones – A Jump-start Guide To…”.

Some topics I really want to learn more about:

HTML5, CSS3, Ruby, Rails, git/git-hub, JavaScript/CoffeeScript, JQuery, JSON, BDD (RSpec, Cucumber)…etc.

I have to believe that others could benefit from them too. I hope to have the first one to share sometime in before the end of this year. I think I’ll start with HTML 5. Any requests?

Scratching Your Own Itch

There’s a saying in open-source software called “scratching your own itch” and it refers to building software that YOU need, not trying to figure out what the rest of the world wants.

That’s very wise advice.

I spent some time in that other frame of mind and it’s frustrating.

I plan on building a web app to manage the tax preparation business that I run on the side from my day job. I plan on building it with Ruby on Rails. Before I do that however, I really need to learn Ruby on Rails as a I am new to it.

So, I could dive right in, learning as I go, fearful of making a mistake on MY application, and I would spend more time thinking than I would coding.  Therefore, I am going to LEARN Rails first, and then I am going to PRACTICE Rails on stuff that doesn’t matter.

If you want to learn Ruby on Rails, there are NUMEROUS resources, many free and some available at very low cost, most of them EXCELLENT. I purchased a screen-cast series and book on PDF from RailsTutorials.  Michael Hartl’s training is top notch and covers not only Ruby as well as Rails, but through osmosis you’ll also learning about curl, git and TextMate.

As far as practicing goes, that’s tomorrow’s post because it’s worthy of a post all its own.

Thread.Sleep();

Learning Ruby

During the day I used .NET but I have recently become completely enamored with Ruby. I don’t know very much about it yet, but it’s syntax and dynamic typing are quite amazing for an old grizzled C#/Java type guy such as me.

 

Even though I most likely won’t use Ruby during my daytime job, just learning certain things about the Ruby community and some of their tools is already paying dividends in the form of discovering tools/methods available to the .NET community that I was not aware of before. In particular I am referring to the Behavior-Driven-Development tools such as NSpec, BDDify and SpecFlow, most of which were largely inspired by the corresponding Ruby tools, RSpec and Cucumber.

In some post soon, I will write about how to use some of these .NET BDD tools because there is precious little content available on how to use them.

 

Thread.Sleep();