Skip to content

Instantly share code, notes, and snippets.

@levicole
Created August 28, 2015 22:06
Show Gist options
  • Select an option

  • Save levicole/304db78978229959ac25 to your computer and use it in GitHub Desktop.

Select an option

Save levicole/304db78978229959ac25 to your computer and use it in GitHub Desktop.

attr_tracker

As a Developer, I want a generator that generates the appropriate migration for tracking attribute changes

When writing a gem that requires a database migration, you should provide a generator for your users so that they don't have to write the migration themselves. Some questions you should ask yourself:

  • What will your data model look like?
  • What should the table be named?
  • Should we allow our users to name the table themselves?
  • Should the generator generate the model as well? Or should we keep the model in the gem?

As a Developer, I want a macro tracks_attribute that let's me specify which attributes I want to track

What is a Macro?

You can think of belongs_to, and has_many as macros. They methods that write code. This style of programming is called meta programming. It's very popular in the Ruby community, but can sometimes be over used. For the gem you are building, you will want to write a macro that gives does a few things:

  • It should associate the model it's called from with the tracked attributes table
  • It should add after save hooks that perisist only the changed attributes we specified to the table

We will generate more methods as we go along, but these will be a good start for our gem.

As a Developer, I want to know the history of a tracked attribute

As a Developer, I want to know what a tracked attribute's value was at any given point in time.

You will be doing more meta programming in this checkpoint (Hooray!?).

You might want to know what an attributes value was at a specific time. In order to do that, we will need to define some methods in our macro:

[attribute name]_at(DateTime)

You can use define method to do this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment