02 Jan 2011

Areas of Focus

In 2009 I created a website to keep track of the simple goals in my life. It was a new way to set goals for me: set one simple goal each day. One Simple Goal was born out of a few days of work, because the concept is simple, and as you all know, I like simplicity. It helps me focus on what matters most, while assisting me in ignoring what doesn’t.

In the lead-up to 2011, I’ve been quietly thinking about what types of resolutions I will make, if any. Typically in the past I’ve shied away from making grandiose resolutions, usually just picking certain directions I’d like my life to flow, and then storing them as high-level ideals about my life. This year will be different.

Not different in that I’ll be buying that gym pass or whatever cliché’s abound when talking about resolutions. No, I am fairly certain I won’t be doing that kind of generalized stuff any time soon. Different because I’ll be more concrete about two things: 1) Focus, and 2) Time-frame. Humans generally love to set goals, and almost always find a way to not achieve them. I’m no different. But when I realized that I still wanted the results of those goals, I stumbled on the idea of making a simple goal every day. No long to-do lists, no lofty “Mount Everest” goals. Simple things, like:

  • Finally paint wall patches I did last August. Go me.
  • Push out some code to OSG. Anything.
  • Write the first of the ruby daily series

Fast-forward to tonight when I realized that OSG is exactly how I should be determining (and implementing) my goals for 2011, with a few tweaks. The first and most noticeable tweak is the time frame. Instead of limiting my goal work to one day, it’ll be 2 to 4 weeks, with a preference to lean on a full month. The focus aspect changes slightly also, as it’s easy to set a specific focus for a given day, but more challenging to do so for a given month. I have a few ideas about how using a system like Scrum can help me achieve real focus with a longer time frame. Keep in mind that as with OSG, the idea is that you have something concrete that you can say: “I did (insert goal here)”. So things like “Become more good looking” don’t count because they’re arbitrary in what their completion may look like. We’re looking for concrete goals, things that (as Seth Godin says) you actually ship. The concept of shipping is paramount.

I threw a list together on SpringPad with a few ideas that I plan on thinking into a little further, but the first month is more or less solidified in my mind as to what I’ll be working on (and yes, it actually is scary to me, in a good way). The over arching focus for 2011 is to develop myself further. 2010 was a banner year for me professionally, and 2011 is poised to be the same or more. But something I felt was lacking was a commitment to be better, not for my career or job, just for me. So 2011’s list looks like that.

One over-arching goal that falls out of this framework is that I want to get back into writing. I was into blogging in ‘07 and ‘08 and thoroughly enjoyed it. Not the page-views and all that garbage, just the act of writing about something. Anything. I want to enjoy it again. With all that in mind, I’ve decided that I’m going to work hard at documenting my ride through 2011 and the way I’m setting this whole thing up. Hopefully it’ll help somebody out, but mostly it’s for my own records and enjoyment.

So here are a few rules for setting goals this year. And yes, I just made them up.

  1. Only concrete goals that can be definitively completed within a month are allowed. Can you answer “Yes” or “No” to the question: Did you ship it?
  2. Do things that are worthwhile and that stretch me. No maintaining of status quo, go beyond.
  3. Planning for the month’s goals happens at the beginning of the month, preferably the first day of the month. Plan only for the current month (iteration).
  4. Retrospectives about what was or wasn’t completed happen at the end of the month. Honesty is key here.
  5. Blog often.
  6. Have Fun.
  7. Write more lists like Ryan ;).

I’ll post more soon. In the meantime, why don’t you go set some simple goals?

22 Sep 2010

Intersecting Arrays in Ruby

Just found a slightly satisfying approach to checking the contents of an array in ruby.

I like using Array#include? to figure out whether or not my given array has a certain entry. Unfortunately, if you want to check if an array has a set of possible values, such as, does it contain :a or :b , you can’t just pass an array of those values. Let me show you what I mean:

  food = [:milk, :bread, :butter]
  food1 = [[:milk, :bread], :butter]
  expected = [:milk, :bread]
  food.include?(:milk) # => true
  food.include?(expected) # => false
  food1.include?(expected) # => true

In other words, include? is very specific about the way it does the matching. But what if I want food.include?(expected) to tell me if food has any of expected ‘s values? Enter Array#& . It doesn’t make include? do anything different, but does give us a simple way to get this newer behavior:

  food = [:milk, :bread, :butter]
  expected = [:milk, :bread]
  (food & expected).size > 0 # => true

Array#& gets the intersection of two arrays (the values that are present in both) and returns a new array containing only those values. You could add this to any Array instance by simply defining your own include_any? method:

  # myapp/lib/ext/array.rb

  class Array
    def include_any? values
      (self & values).size > 0
    end

    def include_all? values
      (self & values).size == values.size
    end
  end

  [:milk, :bread, :butter].include_any?([:milk, :butter]) # => true
  [:milk, :bread, :butter].include_all?([:milk, :butter]) # => false
  [:milk, :bread, :butter].include_all?([:milk, :butter, :bread]) # => true

I cheated and gave you an include_all? method also, which just ensures that all of the expected values are present.

I could’ve used Enumerable#any? but then we’d have to use a block and still use Array#include? . This way, we’re golden.

What cool things have you done with ruby today?

18 Sep 2010

Hooking Instance Methods in Ruby

Everyone and their dog is familiar with ActiveRecord-style callbacks, you know, the kind where you specify you want a particular method or proc to be run before or after a given event on your model. It helps you enforce the principles of code ownership while making it trivial to do the hardwiring, ensuring that code owned by the model is also managed by the model.

I love this kind of programming and recently found that I needed some similar functionality in a particular class, one that wasn’t tied to Active_[Insert your railtie here]. My case was different in that I knew that _any class inheriting from a particular base, which we’ll call HookBase , needed a hardwired hook for every method defined, functionality that needed to run for virtually every instance method call. The following example illustrates my need:

  class HookBase
    def hardwired_hook
      # functionality every method needs
    end
  end

  class MyClass < HookBase
    def find_widget
      # needs setup/teardown help from HookBase
    end
  end

So, operating from the idea that every instance method extending classes implement should have default wrap-around behavior, I got to work. First off, you need to know that ruby has built-in lifecycle hooks on your classes, objects, and modules. Things like included and extended and method_added help you hook in to your code to ensure that the appropriate things are happening on your classes, objects, and modules. So in my case, I needed to know when a method was added to HookBase (or one of its children) so that I could appropriately tap into that code.

method_added is where the meat of the solution lies. When a method is added, ruby fires the method_added call on the object (if any exists), passing it the name of the new method. Keep in mind that this happens after the method has already been created, which is crucial to this solution. We’ll next create a new name from the old name, prepended with some identifier (in this case we chose “hide_”).

We’ll need to check the private_instance_methods array for already defined method names to ensure we’re not duplicating our effort (or clobbering someone elses), as well as checking our own array constant for methods we don’t want to hook. Remember that method_added will be called on every method that is found for HookBase as well as children. I found that there were HookBase methods I had implemented that were supporting this behavior and didn’t need to be hardwired, so I added this to my list of methods to ignore.

If we’ve made it this far, go ahead and alias the old method to the new one, then privatize the new one. Now we can safely redefine the old method without destroying the code it contained. We also now know that no one (except self) can invoke the private method directly, they’ll have to implicitly go through the HookBase first.

Redefining the old method is as simple as using define_method and calling our hardwired_hook method within, passing our new_method (which is privatized), and the old method (for convenience), and any associated arguments and blocks.

The final implementation looks something like this:

  class HookBase
    class << self
      NON_HOOK_METHODS = %w( hardwired_hook some_other_method )

      def method_added old
        new_method = :"hide_#{old}"
        return if (private_instance_methods & [old, new_method]).size > 0 or old =~ /^hide_/ or NON_HOOK_METHODS.include?(old.to_s)
        alias_method new_method, old
        private new_method
        define_method old do |*args, &block|
          hardwired_hook new_method.to_sym, old.to_sym, *args, &block
        end
      end
    end

    private

    # Hardwired handler for all method calls

    def hardwired_hook new_method, old_method, args*, &block
      # perform any before actions
      puts 'doing stuff before method call...'
      # Invoke the privatized method
      __send__ new_method, *args, &block
      # perform any after actions
      puts 'doing stuff after the method call...'
    end
  end

  class MyClass < HookBase
    def find_widget
      puts 'finding widget...'
    end
  end

  MyClass.new.find_widget
  # doing stuff before method call...
  # finding widget...
  # doing stuff after the method call...

The great thing about this approach is you may not even care about hardwiring anything, but just want to provide hooking functionality. If that’s the case, simply define a class method in HookBase to register a hook (such as before or after ), optionally accepting an :only or :except list of methods. Internally store the blocks passed and invoke them in the hardwired_hook method either before or after the method call.

Let me know if you have any comments or different approaches. Happy hacking!

UPDATE: Forgot that method_added needs to be defined in class << self to work properly. Also updated to use the Array#& intersection method I described in Intersecting arrays in ruby instead of using Array#include? .

02 Jun 2010

Variable-length Method Arguments in Ruby

In yesterday’s post regarding the four things you should know about ruby methods, I covered some basics about ruby method definitions. For this post, I just wanted to go into a little more detail here with some of the things I left off the table that came to me later.

Variable-length arguments

Number three on our list of things you should know, we talked about variable-length arguments, also known as the array-collected parameter. At least, that’s what I call it… sometimes. This cool feature allows you to pass any number of arguments to a ruby method and have all the unmapped parameters get collected into a single parameter which becomes an array of the values that were passed. Whew! That was a mouthful.

  def log_all(*lines)
    lines.each{|line| @logger.info(line)}
  end

  log_all 'foo', 'bar', 'baz', 'qux'

  # File: logs/your_log_file.log
  # foo
  # bar
  # baz
  # qux

This is neat, no doubt, but what if you don’t want to specify each value individually to the array-collected parameter in the method call? Say for instance, in the previous example, I already had the values 'foo' , 'bar' , 'baz' , and 'qux' in an array. Ruby allows you to pass the array through as a pre-collected array of values. The only thing to do is pass the array as a single parameter, prefixed by an asterisk ( * ).

  def log_all(*lines)
    lines.each{|line| @logger.info(line)}
  end

  # values are predefined
  values = ['foo', 'bar', 'baz', 'qux']

  # Don't forget the asterisk!
  log_all *values

If you were to indeed forget the asterisk before the values array being passed, log\_all ‘s lines parameter would still be an array, but would only contain one element: the array you passed. So in order to get to it you’d either have to flatten lines or call the 0th index on it, which sort of defeats the purpose.

Don’t forget blocks, lambdas, and procs!

This array-collection technique to method parameter definition is not only confined to normal methods, but also to ruby’s trio of anonymous function definitions: blocks, lambdas, and procs. Take the same example from above, with log\_all rewritten as a lambda.

  log_all = lambda do |*lines|
    lines.each{|line| @logger.info(line)}
  end

  # values are predefined
  values = ['foo', 'bar', 'baz', 'qux']

  # Don't forget the asterisk!
  log_all.call *values

You can even do this with ActiveRecord named_scopes, which is wicked cool.

  class User < ActiveRecord::Base
    named_scope :with_names_like, lambda do |*names|
      { :conditions => names.collect{|name| "lower(name) like '%?%'"}.join(' OR ').to_a.push(names).flatten! }
    end
  end

  User.all.with_names_like 'jeff', 'jose', 'jill'

  # Creates a condition sql string like so:
  # WHERE (lower(name) like '%jeff%' OR lower(name) like '%jose%' OR lower(name) like '%jill%')

I’m interested to know what other ways you’ve come up with to use this technique. Please leave a comment below if you have any questions or examples of your own work.