Displaying dates with a badge. 09 Jan 2014

One of my recent client projects needed a cool, stylized calendar badge for displaying dates. This was going to be used all over the app, so I decided to helperize it. It came out pretty damn nice, so here's how they look.

Here's the calendar_badge with a ruby date object:

calendar_badge with date object

... and without a ruby date object:

calendar_badge with date object


If we have a date object, format the date and emit a span with the month as a class. Title should be the full date, so hovering shows the date with year. It bugs the crap out of me when people forget to do this... or worse yet, don't include a date on blog posts. I really hate that!

def calendar_badge date
  if date.respond_to? 'strftime'  # This is a date object. Do date-y things.
    content_tag :span, date.strftime('%-d'),
                title: date.strftime('%-m/%-d/%Y'),
                class: "calendar-badge #{date.strftime('%b').downcase}"

  else                            # Not a date object. Assume it's a string.
    content_tag :span, date,
                class: 'calendar-badge no-month'


We use icon fonts for each month. I definitely could have done this with just CSS, but retaining the designer's font (which was one-off for these badges) was important. Anytime you're adding a @font-face for some silly one-off thing you should think about how you could save an HTTP request and some bandwidth by accomplishing it with your existing resources — sprites, iconfonts, etc.

@mixin calendar-badge-size ($height) {
  // Keep everything sized correctly
  height:      $height;
  width:       $height * 1.0625;
  font-size:   $height * 0.4375;
  line-height: $height * 1.3125;

  &:before { font-size: $height; }

.calendar-badge {
  @include calendar-badge-size(32px);
  display:     inline-block;
  position:    relative;
  text-align:  center;
  font-family: $primary-typeface-bold;

  &:before {
    font-family: 'iconfont';
    text-align:  center;
    position:    absolute;
    top:         0;
    left:        0;
    right:       0;
    line-height: 1em;

  &:before     { @include iconfont-cal; }
  &.jan:before { @include iconfont-cal-jan; }
  &.feb:before { @include iconfont-cal-feb; }
  &.mar:before { @include iconfont-cal-mar; }
  &.apr:before { @include iconfont-cal-apr; }
  &.may:before { @include iconfont-cal-may; }
  &.jun:before { @include iconfont-cal-jun; }
  &.jul:before { @include iconfont-cal-jul; }
  &.aug:before { @include iconfont-cal-aug; }
  &.sep:before { @include iconfont-cal-sep; }
  &.oct:before { @include iconfont-cal-oct; }
  &.nov:before { @include iconfont-cal-nov; }
  &.dec:before { @include iconfont-cal-dec; }


It's as simple as just calling the helper with a date object.

When we want a nil date to be displayed we call it with a dash instead of a date object.

  %label Current Date
  = calendar_badge Time.now
comments powered by Disqus