Unless you have ultra simplistic needs, (and are using Rails) I always recommend using the fantastic will_paginate plugin for paginating ActiveRecord, and even non-ActiveRecord collections! But, if you have a basic need to to page an array, you could open up the Array class and add this method:

class Array
  def page(pg, offset = 10)
    self[((pg-1)*offset)..((pg*offset)-1)]
  end
end

This is a beautiful little method that adds #page to all arrays, and can be utilized like this:

my_array = [1,2,3,4,5, ... ,20,21,22,23,24,25]
my_array.page(1) #=> [1,2,3,4,5,6,7,8,9,10]
OR
my_array.page(1, 5) #=> [1,2,3,4,5]

Feel free to use this if you like it!

At Caring.com, we write our view templates using Haml and Sass (with Chris Eppstein’s Compass CSS Framework). It was a little strange to get used to at first, especially coming from tag-based/ERB-style frontend templating, but I have found that it is surprisingly straightforward, and succinct. TextMate, which is a fabulous text editor for rails and ruby, has two bundles that I use constantly that make my life easier (code coloring especially) in both Haml and Sass.

I am writing this blog post to share the bundles I use everyday with you, and so that I can remember where they live, for myself.

For Sass integration I use this bundle by seaofclouds:
git clone git://github.com/seaofclouds/sass-textmate-bundle.git "Ruby Saas.tmbundle"

For Haml integration, I use the “official” one provided by MacroMates (the creators of TextMate):
svn co "http://macromates.com/svn/Bundles/trunk/Bundles/Ruby Haml.tmbundle"

Clearly, you need to have both Subversion and Git installed to install these plugins, however you may be able to travel to github and download a zip file if need be.

Thanks so much everyone for submitting your Fibonacci examples! One of the reasons why I asked everyone to do this is because it gives me (and all of us) a chance to learn about different approaches and different languages. So, in case you haven’t figured it out, it was sort of a trick question.

Fibonacci is generally very fast, unless you are over-architecting the solution. Let me show you what I mean:

def fibo(n)
  (!(n>2)) ? n : fibo(n-1)+fibo(n-2)
end
 
37.times do |i|
  puts "n=#{i} => #{fibo(i)}"
end

This was my first attempt. Its a beautifully complex execution of the algorithm, using recursion. However, notice that I am not storing any of the values that I am calculating? That causes the processor to go crazy around time 30. This would be what I call a classic example of over-architecting a simple problem.

But its cool right? :)

Here is my faster, smarter, more performant version:

$fibs = [];
 
 
def fibo_calc(n)
  (!(n>2)) ? n : fibonacci(n-1)+fibonacci(n-2)
end
 
def fibonacci(n)
  if $fibs[n]
    return $fibs[n]
  else
    x = fibo_calc(n)
    $fibs[n] = x
    return x
  end
end
 
37.times do |i|
  puts "n=#{i} => #{fibonacci(i)}"
end

This is much much much faster, and can hit 30,000 iterations without missing a beat. The cooler thing too is that I can mix up the 30,000 integers that its calculating for, and it can run a “shortcut” using the array. Very cool.

So that was my nerd realization of the month. Of course, there are a billion ways to skin an algorithm, but sometimes the most concise or technically interesting way, is the slowest.

Anyone else out there tired of Twitter-spam? Every new web 2.0+ application that hits the web today asks you for your twitter credentials so they can post a 140 character spam about some various task you are performing at some website I don’t care about. However, there are times when I do care about those other various tasks my friends are performing on various websites, and that’s where FriendFeed comes in.

But I ask you, WHY BOTHER? Why am I going over to FriendFeed when I have a perfectly good Twitter timeline, full of friends I already know and trust, and chock-full of useless and semi-interesting pieces of information that I can’t seem to live without. Why are we duplicating all that information, when we could combine it into a master timeline (using Twitter), through a much more secure medium?

The as it stands today, If you want to broadcast your activities on a specific site through Twitter, you have to be ready to hand them over your username and password, that way they can essentially pretend to be you and make a post on your behalf. For some reason, that doesn’t seem to phase most people, but the ramifications of that act are sort of dangerous. As you may have heard, Twitter and the people who use it control many different spheres of influence, and that information falling into the wrong (and insecure) hands could be disastrous.

This is 2009! We’ve solved these sorts of problems in the past, lets put our thinking caps on! API, bitches. Twitter needs to introduce an API so that third-party vendors can post to your Twitter account without you having to fork over any nuclear secrets. Flickr has figured out how to do this very well…eons ago

“But Derek! Didn’t you start this post off by saying you hate Twitter-spam?”

Yes, I do. Thats why the next thing we need Twitter to do is setup “Twitter Feeds”, which will be where all of the twitter-spam is sent and categorized for when that information is sought after. Don’t think anyone will go out of their way to see that information? Friendfeed.com and its 5 million dollars in funding beg to differ. Twitter is the most natural place for this information to exist!

Why bother with FriendFeed at all when your “Twitter Feed” can say the last netflix movie you’ve watched, or that digg article about “the top 10 cats laying on their backs” that you thought was so awesome. This information, once officially supported by Twitter, can then be properly segmented and keeps my timeline about what it should be, you know, pictures of my cat and how many times I hate internet explorer.

This idea, however, is going to seriously impact the current load that Twitter is used to, even at 1.2 million new users a month (I read that somewhere, could be wrong). FriendFeed works through RSS, so the responsibility of that information’s existence is placed on the RSS provider, and not FriendFeed. So I could imagine their would be a substantial increase in data that is sent to Twitter, but having said that, they seem to be doing pretty good at handling themselves these days, and that would only make Google want to swallow them whole faster.

So basically, Twitter needs a ping API, and the pings sent by the API (that are theoretically web 2.0 spam) need to be segmented into their own grouping, that way we can do away with social networking social networks and utilize a popular technology we already love.

I am absolutely excited about this news!! Yesterday, both the Merb and Rails camp have announced the news, so I won’t bother reiterating whats already been said. I’d rather talk about some of the major points that really get me excited about this announcement and how it is going to impact not only the history of Ruby on the web, but potentially web programming from this point on.

Fully Modular Core
I am happy that DHH and co have embraced the modularity concept that is one of the core ideals of the Merb project. Now, if you don’t want to Prototype as your JavaScript system, you can toss it and stick in jQuery, which will run 100% as well as the default. Although its 100% modular, the “Rails Way” is going to give you a smart set of defaults that you can completely customize to fit your needs!

I must admit, this is one of the sexiest things about Merb.

Speed is Quickly Becoming a Non-Issue
In the Ruby world, there is a ton of exciting innovation going on around building some amazing virtual machine technologies and really pushing the limits of what can be done with such an expressive and dynamic language. Also, we are seeing some fantastic developments on the deployment side of things that are making it not only extremely easy to deploy, but faster the serve requests as well.

So naturally, the next place to go for optimization is our framework. Merb has already made a ton of strides in making a thread-safe, and extremely fast framework. This development stack is going to scream in 2009!

AmazingĀ  Base and Synergy
Between the Merb and Rails technologies and groups, there is going to be all kinds of new things to learn and all sorts of great people to work with and learn from. I am absolutely excited about what all of this means for the Ruby/Rails/Merb communities. We have got one of the fastest growing and fully-integrated technology stacks available for the internet today as an open source foundation.

With the emerging ecosystem of technology and thought that is occurring in this community, we are going to be seeing some amazing things in 2009.

I have been rolling around the idea of starting up more freelancing to try to bolster my savings for the coming years, so I’ve decided to take on more consulting work. For an indepth look at my work experience and skills, please visit my linkedin profile, here are some highlights.

- 5 years relevant web development experience
I’ve worked a ton with the web, I’ve done everything from ColdFusion to my current favorite, Ruby (and Rails). I have a lot of experience working with JavaScript and XHTML/CSS, very comfortable doing frontend and backend development, as well as database work (although, I don’t want to use the term DBA). If you’d like to see my portfolio, contact me directly.

- Did I mention I love Ruby?
I have done a lot of work with Ruby in the past couple of years, I was highlighted on the RailsEnvy podcast a few weeks ago for a modest open source contribution I made called SmartMonth. I’ve worked on some medium-sized rails deployments, and am looking to grow my portfolio.

- Plays well with others
I love working on small, motivated teams. I always enjoy adding (and learning) from the synergy of a great team. I also test all of my code (quite thoroughly) and won’t break “the build”.

- UNIX Aficionado
I love UNIX, and its my deployment environment of choice, I’ve got a lot of experience working with Capistrano, and am very adamant about automating things wherever possible, and documenting things thoroughly.

- Entrepreneurial-Minded
I have a passion for growing things, I am a very dedicated team member, and am also very aware of the needs of startup-oriented businesses, I’ve worked with a few startups at this point, and have gathered a decent amount of relevant experience helping companies and products grow.

If I sound at all interesting to you, please don’t hesitate to drop me a line, or if you know someone who might be interested in hiring me, please forward my information along and I’ll send you a Christmas card.
Thanks everyone!

Today I was faced with an interesting dilemma, how does one programmatically define migrations into a plugin so you can essentially “plug-n-play”. I did a little bit of research into Rails Engines, and I wasn’t too terribly excited about the notion of having a dependency for such a small plugin, if this were something more integrated…I’d probably use it, but for this, I really only need to have these migrations run once you’ve installed the plugin, and be on my way.

So, I decided to do a little bit of research on the ActiveRecord::Migrator class to see how I could approach programmatically executing the migration outside of the standard rake task, so I could build my own custom migration rake task for my plugin.

It turns out, there are a bunch of functions you can utilize to build your own custom migration tasks for your plugin, that I wasn’t immediately aware of. Here is how I did it:

namespace :myplugin do
  desc "migrates my plugin's migration files into the database."
  task :migrate => :environment do
      ActiveRecord::Migrator.migrate(File.expand_path(File.dirname(__FILE__) + "/../db/migrate"))
      Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
  end
end

I simply saved that block of code into my plugin’s /tasks folder and named it custom_migration.rake. Next, I went to the root of my application and ran rake myplugin:migrate, and huzzah! it worked!

Nothing too amazing, and I actually based this entirely on the vanilla db:migrate function. The first line of the task essentially tells the ActiveRecord Migrator to search through my plugin’s db/migrate folder for any migration files it can find, and then brings all of them up! It would be nice if the vanilla db:migrate supported a MIGRATIONS_PATH constant so we could just use the same mechanics and build on top of them, rather than essentially re-write them just to do this.

OR better yet, wouldn’t it be nice if rails db:migrate actually scanned our plugins directory for migration files as well? That sounds like the best option to me.

Now, I am not sure if this is “the ruby way” to handle this problem, and as I stated earlier, Rails Engines is probably the way to go if you have a much larger plugin you are designing, but for me, this seemed to work just fine.

Limitations

There are some limitations to that custom task. For instance, if you were to run db:rollback, it would not be aware of the migration files that I have previously run that live within my plugin, you’d have to build another custom task to manage revoking the migrations you installed. Also, if they end up changing the way you actually migrate migrations, you might be screwed. But, alas, here is hoping for that MIGRATIONS_PATH constant!

Thanks to the fellows over at Rails Envy for doing a quick spot on my SmartMonth plugin! I actually had never heard of Chronic until they had mentioned it. I could see how this would actually go very well with a gem like that!

Speaking of SmartMonth, I have a couple of cool optimizations I plan to make in the new week, so stay tuned if you are interested!

Our big project at Panoctagon has a lot to do with time and dates, so we’ve been developing a series of Rails plugins that make our jobs easier. I had a lot of fun building this one, and I could see other people finding this interesting, so we decided to open source this one. I think it’d make a great addition to Rails core (if I do say so myself :P), but I am not really up to all the effort involved. Instead I created a simple to use, documented, and tested plugin that works with Rails!

So what does it do? Basically, it makes date month values more meaningful by adding a new Month class that can do complex(ish) calculations against the days of the month for you. It also allows you to treat a Month as an enumerable container, allowing you to iterate through the days of the month like an array.

Lets peek at some example snippets:

Getting The First Tuesday of September 2009

1
2
    Month.september(2009).first_tuesday #=> Date object
    Month.new(9,2009).first(:tuesday) #=> Date object

Getting Every Friday in August 2008

1
2
    Month.august.every_friday #=> Array of Date objects
    Month.new("August").every(:friday) #=> Array of Date objects

Getting Every Thursday and Saturday in June 2007

1
2
    Month.june(2007).every_thursday_and_saturday #=> Hash of Arrays of Date objects
    Month.new("June",2007).every(:thursday,:friday) #=> Hash of Arrays of Date objects

Getting The Last Monday in April 2005

1
2
    Month.april(2005).last_monday #=> Date object
    Month.new("April",2005).last(:monday) #=> Date object

Enumerating Through the Month of August 2008

1
2
3
4
5
   month = Time.now.month #=> Month object of the current time requested
   month.each do |day|
     day.to_s #=> Week day name ie: Saturday, Sunday, etc.
     day.to_i #=> Date value in context of the month ie: 1..31
   end

Other Odds and Ends

1
2
3
4
5
  Month.april.size #=> total number of days in that month
  Month.august.next #=> returns a month object populated with August
  Time.now.month #=> returns the current month in context to the #now response
  Month[5] #=> May Month object access as array index
  Month[:april] #=> April month object access as hash key

So, as you can see, it saves a lot of time and calculations and keeps it easy for you to treat months as essentially a container! Really useful for doing complex calculations against dates.

If you would like to use my plugin, feel free, I’ve released it under MIT, and its located at my github account. Please give me some props if you do, or send me a line.

If you are interested in my rdoc documentation, check our company’s documentation server. Let me know what you guys think!

10 points for most original title, ever.

Lately, my company and I have been looking into the benefits of switching to Git for source code repository management. Its currently the new “hotness” of the hacker world, and with some of the claims that I’ve read, its pretty hard to ignore.

Linus Torvalds has made a few references to how much he hates tools like Subversion and CVS, and he has a lot of interesting reasons for feeling the way he does. I don’t agree with everything, but then again, I am not writing a kernel. Subversion has worked great for me and my team in the past, but we are definitely starting to envy some of the Git advantages.

Its indisputable that Git makes it unbelievably easy to branch and tag your repositories, hands down. The bigger and more integrated my codebase and team is getting, the more of crucial of a feature that is to us. Decentralization is not a big deal to me. Frankly, I never am really “off the grid”, so most times I just do git commit followed by a push.

Fortunately for us, Unfuddle supports Git now, so its easy for us to use our existing project management tool with this new technology, at no extra investment! But, I have to take a moment to say, GitHub is definitely pretty killer. Unfuddle’s support for Git is new and will improve over time, but I am very very impressed with how well GitHub has nailed the integration. The biggest reason for me to move (some) of my code to GitHub is for the public aspect of it. From this point forward, I will be posting my company and I’s open source contributions there. Mostly because Unfuddle doesn’t provide external access to projects in the same way, which is actually sort of strange in my opinion.

Maybe in the future I will be so inclined to product an Unfuddle-Git bridge to keep my repositories (edit: there is one already, why isn’t this a part of GitHub yet?!) synchronized, for projects I plan to open source. Overall, I am pretty happy with Git, I think my initial impressions of it were tainted by the “growing pains” I experienced while trying to get it to work with Unfuddle. Seriously, with GitHub I was up and running with the repo in under 2 minutes!

You can check out my repositories here. There is one project there now that I haven’t talked about too much yet, mostly because I just built and released it in the last 72 hours. More on that soon!

keep looking »