Ruby Forwardable deep dive

The Forwardable library is one of my favorite tools from Ruby's standard library both for simplifying my own code and learning how to make simple libraries.

I find that the best way to understand how code works is to first understand why it exists and how you use it. In a previous article I wrote about the value of using Forwardable. It takes code like this:

def street
      address.street
    end

    def city
      address.city
    end

    def state
      address.state
    end

And makes it as short as this:

delegate [:street, :city, :state] => :address

Shrinking our code without losing behavior is a great feature which Forwardable provides. So how does it work?

Modules and their context

Forwardable is a module, which can be used to add behavior to an object. Most of the of modules I see tend to be used like this:

class Person
      include SuperSpecial
    end

But Forwardable is different and is designed to be used with the extend method.

require 'forwardable'
    class Person
      extend Forwardable
    end

Using extend includes the module into the singleton_class of the current object. There's a bit more to it than that, but here's a simple model to keep in mind: use include in your class to add instance methods; use extend in your class to add class methods.

Now that we have that out of the way, to use Forwardable, use extend.

Defining forwarding rules

My most often used feature of Forwardable is the one you saw above: delegate. It accepts a hash where the keys can be symbol or string method names, or an array of symbols and strings. The values provided are accessors for the object to which you'll be forwarding the method names.

class Person
      extend Forwardable

      delegate [:message_to_forward, :another_method_name] => :object_to_receive_message,
                :single_method => :other_object
    end

Other shortcuts

Forwardable provides a few methods, and most commonly you'll see their shortened versions: delegate, def_delegator, and def_delegators. These are actually alias methods of the originals.

alias delegate instance_delegate
    alias def_delegators def_instance_delegators
    alias def_delegator def_instance_delegator

The delegate method we reviewed above is a bit of a shortcut for similar behavior that other methods provide in Forwardable.

The def_delegators method accepts multiple arguments but it's sometimes hard for me to remember that one argument in particular is important. The first argument is the reference to the related object, the next arguments are used to create methods to forward.

class SpecialCollection
      extend Forwardable

      def_delegators :@collection, :clear, :first, :push, :shift, :size
      # The above is equivalent to:
      delegate [:clear, :first, :push, :shift, :size] => :@collection
    end

As you can see, with delegate there's a visual separation between the accessor and the list of methods.

There's more of a difference between delegate and def_delegators too.

def instance_delegate(hash) # aliased as delegate
      hash.each{ |methods, accessor|
        methods = [methods] unless methods.respond_to?(:each)
        methods.each{ |method|
          def_instance_delegator(accessor, method)
        }
      }
    end

Here the code loops through the hash argument changing the keys into arrays of methods if they aren't already arrays, and then calls the def_instance_delegator method for each item in the array. Here's what def_instance_delegators looks like. Note that this is the plural version:

def def_instance_delegators(accessor, *methods) # aliased as def_delegators
      methods.delete("__send__")
      methods.delete("__id__")
      for method in methods
        def_instance_delegator(accessor, method)
      end
    end

This method speficially restricts the use of __send__ and __id__ in forwarded messages. These methods are particularly important in communicating with the forwarding object and determining its identity. If you only used delegate and (for some strange reason) you specify either of __send__ or __id__ then those methods will pass right through. That might do exactly what you want or it might introduce some buggy behavior. This is mostly easy to avoid since you'll likely specify all the methods you need.

The different behavior is important to know, however, if you want to do a blanket forward for all methods from another class of objects:

class SpecialCollection
      extend Forwardable

      def_delegators :@collection, *Array.instance_methods
      # The above is equivalent to:
      delegate [*Array.instance_methods] => :@collection
    end

If you do that, you'll likely see warnings from Ruby like this:

warning: redefining `__send__' may cause serious problems

Don't say Ruby didn't warn you!

But def_delegators is a plural version of def_delegator which provides more options than the two we've been reviewing.

class SpecialCollection
      extend Forwardable

      def_delegator :@collection, :clear, :remove
      def_delegator :@collection, :first
    end

The method def_delegator accepts only three arguments. The first is the accessor for the related object (which will receive the forwarded message) and the second is the name of the message to be sent to the related object. The third argument is the name of the method to be created on the current class and is optional; if you don't specify it then the second argument will be used.

Here's what the above def_delegator configurations would look like if you wrote out the feature yourself:

class SpecialCollection
      extend Forwardable

      # def_delegator :@collection, :clear, :remove
      def remove
        @collection.clear
      end

      # def_delegator :@collection, :first
      def first
        @collection.first
      end
    end

You can see how the optional third argument is used as the name of the method on your class (e.g. remove instead of clear).

How the methods are created

We looked at how Forwardable adds class methods to your class. Let's look at the most important one:

def def_instance_delegator(accessor, method, ali = method)
      line_no = __LINE__; str = %{
        def #{ali}(*args, &block)
          begin
            #{accessor}.__send__(:#{method}, *args, &block)
          rescue Exception
            $@.delete_if{|s| Forwardable::FILE_REGEXP =~ s} unless Forwardable::debug
            ::Kernel::raise
          end
        end
      }
      # If it's not a class or module, it's an instance
      begin
        module_eval(str, __FILE__, line_no)
      rescue
        instance_eval(str, __FILE__, line_no)
      end
    end

It looks like a lot, and it is, but let's strip it down to it's simplest form rather than review everything at once. Here's a simpler version:

def def_instance_delegator(accessor, method, ali = method)
      str = %{
        def #{ali}(*args, &block)
          #{accessor}.__send__(:#{method}, *args, &block)
        end
      }
      module_eval(str, __FILE__, __LINE__)
    end

Remembering, of course, that def_instance_delegator is aliased as def_delegator we can see that a string is created which represents what the method definition will be and saved to the str variable. Then then that variable is passed into module_eval.

It's good to know that module_eval is the same as class_eval because I know I often see class_eval but rarely see the other. Regardless, class_eval is merely an alias for module_eval.

The string for the generated method is used by module_eval to create the actual instance method. It evaluates the string and turns it into Ruby code.

Taking this command def_delegator :@collection, :clear, :remove here's what string will be generated:

%{
      def remove(*args, &block)
        @collection.__send__(:clear, *args, &block)
      end
    }

Now it's a bit clearer what's going to be created.

If you're not familiar with __send__, know that it's also aliased as send. If you need to use the send method to match your domain language, you can use it and rely on __send__ for the original behavior. Here, the Forwardable code is cautiously avoiding any clashes with your domain language just in case you do use "send" as a behavior for some object in your system.

Maybe you're scratching your head about what either of those methods are at all. What the heck is send anyway!?

The simplest way to describe it is to show it. This @collection.__send__(:clear, *args, &block) is equivalent to:

@collection.clear(*args, &block)

All Ruby objects accept messages via the __send__ method. It just so happens that you can use the dot notation to send messages too. For any method in your object, you could pass it's name as a string or symbol to __send__ and it would work the same.

It's important to note that using __send__ or send will run private methods as well. If the clear method on @collection is marked as private, the use of __send__ will circumvent that.

The methods defined by Forwardable will accept any arguments as specified by *args. And each method may optionally accept a block as referred to in &block.

It's likely that the acceptance of any arguments and block will not affect your use of the forwarding method, but it's good to know. If you send more arguments than the receiving method accepts, your forwarding method will happily pass them along and your receiving method will raise an ArgumentError.

Managing errors

Forwardable maintains a regular expression that it uses to strip out references to itself in error messages.

FILE_REGEXP = %r"#{Regexp.quote(__FILE__)}"

This creates a regular expression where the current file path as specified by __FILE__ is escaped for characters which might interfere with a regular expression.

That seems a bit useless by itself, but remembering the original implementation of def_instance_delegator we'll see how it's used:

str = %{
      def #{ali}(*args, &block)
        begin
          #{accessor}.__send__(:#{method}, *args, &block)
        rescue Exception
          $@.delete_if{|s| Forwardable::FILE_REGEXP =~ s} unless Forwardable::debug
          ::Kernel::raise
        end
      end
    }

This code recues any exceptions from the forwarded message and removes references to the Forwardable file.

The $@ or "dollar-at" global variable in Ruby refers to the backtrace for the last exception raised. A backtrace is an array of filenames plus their relevant line numbers and other reference information. Forwardable defines these forwarding methods to remove any lines which mention Forwardable itself. When your receive an error, you'll want the error to point to your code, and not the code from the library which generated it.

Looking at this implementation we can also see a reference to Forwardable::debug which when set to a truthy value will not remove the Forwardable lines from the backtrace. Just use Forwardable.debug = true if you run into trouble and want to see the full errors. I've never needed that myself, but at least it's there.

The next thing to do, of course, is to re-raise the cleaned up backtrace. Again Forwardable will be careful to avoid any overrides you may have defined for a method named raise and explicitly uses ::Kernel::raise.

The double colon preceding Kernel tells the Ruby interpreter to search from the top-level namespace for Kernel. That means that if, for some crazy reason, you've defined a Kernel underneath some other module name (such as MyApp::Kernel) then Forwardable will use the standard behavior for raise as defined in Ruby's Kernel and not yours. That makes for predictable behavior.

Applying the generated methods

After creating the strings for the forwarding methods, Forwardable will attempt to use module_eval to define the methods.

# If it's not a class or module, it's an instance
    begin
      module_eval(str, __FILE__, line_no)
    rescue
      instance_eval(str, __FILE__, line_no)
    end

If the use of module_eval raises an error, then it will fallback to instance_eval.

I've yet to find a place where I've needed this instance eval feature, but it's good to know about. What this means is that not only can you extend a class or module with Forwardable, but you can extend an individual object with it too.

object = Object.new
    object.extend(Forwardable)
    object.def_delegator ...

This code works, depending of course on what you put in your def_delegator call.

Forwarding at the class or module level

All these shortcuts for defining methods are great, but they only work for instances of objects.

Fortunately forwardable.rb also provides SingleForwardable, specifically designed for use with modules (classes are modules too).

class Person
      extend Forwardable
      extend SingleForwardable
    end

In the above sample you can see that Person is extended with both Forwardable and SingleForwardable. This means that this class can use shortcuts for forwarding methods for both instances and the class itself.

The reason this library defines those longform methods like def_instance_delegator instead of just def_delegator is for a scenario like this. If you wanted to use def_delegator and those methods were not aliased, you'd need to choose only one part of this library.

class Person
      extend Forwardable
      extend SingleForwardable

      single_delegate [:store_exception] => :ExceptionTracker
      instance_delegate [:street, :city, :state] => :address
    end

As you can probably guess from the above code, the names of each library's methods matter.

alias delegate single_delegate
    alias def_delegators def_single_delegators
    alias def_delegator def_single_delegator

If you use both Forwardable and SingleForwardable, you'll want to avoid the shortened versions like delegate and be more specific by using instance_delegate for Forwardable, or single_delegate for SingleForwardable.

If you liked this article, please join my mailing list at http://clean-ruby.com or pick up the book today!

Avoiding clever mistakes when displaying data with missing values

In a previous article I showed a snippet of code I’ve used for displaying address information. There were some tricks to getting it right that are valuable to know when you have to handle missing data.

Here’s the problem, and how to solve it.

Let’s setup some simple data to use:

street = "123 Main St."
    city = "Arlington"
    province = "VA"
    postal_code = "222222"

The original implementation of displaying an address looked like this:

"".tap do |string|
      string << street unless street.nil?
      string << city unless city.nil?
      string << province unless province.nil?
      string << postal_code unless postal_code.nil?
    end

While that code will skip missing data if there is any, it will just mash all the bits together creating this:

"123 Main St.ArlingtonVA22222"

That’s not particularly helpful for displaying a readable address. I’m looking for it to display like this:

"123 Main St.
    Arlington, VA 22222"

Here’s what I tried next:

[street, [city, [province, postal_code].join(' ')].join(', ')].join("\n")

Thinking I was very clever, I ran the code with complete data and it worked quite well.

When I ran it with incomplete data I found that it didn’t work the way I expected. For example, if the city value was nil, I got this:

"123 Main St.
    , VA 22222"

That leading comma is just visual noise, so we need to remove that. Realizing that I had nil values in my arrays, I knew I could reach for the compact method to strip them out. After compacting the array, the join wouldn’t have nil values to address; they’d be gone.

[street, [city, [province, postal_code].compact.join(' ')].compact.join(', ')].compact.join("\n")

This worked perfectly, to remove the leading comma:

"123 Main St.
    VA 22222"

Just to be sure I got it right, I began checking other data. Next, with the city set to “Arlington” and this time with the province and postal_code set to nil I saw this:

"123 Main St.
    Arlington, "

Ugh! Now I had a trailing comma. Why wasn’t this working!? Using compact should remove the nil values.

The problem was that I had an empty array for the province and postal_code. That meant that with both values removed from the array using compact, this was happening:

[].join(' ') #=> ""

And because that empty array returned a value of an empty string, I was joining the city value with an empty string. In this case, compact was doing nothing for me.

[city, [province, postal_code].compact.join(' ')].compact.join(', ')
    # is the same as:

    [city, ""].compact.join(', ')]
    # which yields:

    "Arlington, "

So there it was. Finally I found my problem that what I thought was nil, wasn’t.

I decided to change the values to nil if they were empty strings:

province_and_postal_code = [province, postal_code].compact.join(' ')
    province_and_postal_code = nil if province_and_postal_code.empty?

    city_province_postal_code = [city, province_and_postal_code].compact.join(', ')
    city_province_postal_code = nil if city_province_postal_code.empty?

    [street, city_province_postal_code].compact.join("\n")

Finally, I got the output I needed:

"123 Main St.
    Arlington"

    "123 Main St.
    VA 22222"

    "123 Main St.
    Arlington, VA 22222"

My clever one-liner gave me unexpected behavior. While it was nice and short, it was also wrong. Eventually I ended up with code which is not just correct, but much more readable too. You might have your own preferences for how to handle these nil values. What would you do differently?

Enforcing encapsulation with East-oriented Code

Often our programs become complicated inadventently. We don't intend to put things it the wrong place, it just seems to happen.

Most of the time it happens to me when I allow my objects to leak information and eventually their responsibilities.

In recent articles I showed code that handled displaying address details and how to separate the responsibility for formatting from the responsibility for data. But there's still a problem which would allow me or someone else to unintentionally leak responsibility from these objects.

It's a good idea to be guarded against how much you reveal from an object; you never know how someone might use it in the future.

In our Template code, we provide a number of values about the object: province, postal_code, city, street, apartment, province_and_postal_code, city_province_postal_code, address_lines, and display_address. With each attribute provided, we introduce the ability to other objects to query the information and make decsions based upon the answer.

It's far too easy to write these types of queries:

if template.province == "..."
if template.city == "..." && template.postal_code == "..."
if template.city_province_postal_code.include?("...")

But what would our code look like if we couldn't do this? What if there were no questions to ask?

What if the only accessible information from our template was the display_address used to show the formatted data?

require 'forwardable'
class Template
  extend Forwardable

  def display_address
    address_lines.join("\n")
  end

  def with_address(address)
    @address = address
  end

  private
  delegate [:province, :postal_code, :city, :street, :apartment] => :@address

  def province_and_postal_code
    # ...
  end

  def city_province_postal_code
    # ...
  end

  def address_lines
    [street, apartment, city_province_postal_code].compact
  end
end

By moving most of our methods under the private keyword, our Template interface has shrunk significantly. Now all we'll have to handle and all other objects will need to know about is the display_address and with_address methods.

East vs. West

The changes we made make a significant restriction on the questions that we can ask about an object. This is where the idea of East-orientation comes in.

If we imagine a compass applied to our source code we'd see that any query, any if, will send the information flowing westward.

# <---- information travels West
if template.city == "..."

The if handles the execution of the algorithm. But by removing methods from the public interface which provide attributes like above, we better encapsulate the data in the target object. Our template here could not answer a question about its city attribute.

Instead, the code which uses the template would be forced to command the template to perform a particular action. The body of the if could instead become a method on the template object.

# ----> information travels East
template.perform_action

The template can make it's own decisions about what to do when told to perform some action.

Enforce encapsulation with return values

An easy way to ensure that our code encourages commands, discourages queries, and enforces encapsulation is to control the return values of our methods.

The best thing to return is not necessarily the result of the method, but the object performing the method. It's as simple as adding self to the end of the method block.

Here's what that might look like:

class Template
  def with_address(address)
    @address = address
    self
  end
end

By adding self there, each time we set the address value object using with_address we are given the object itself back, instead of the value that we passed to it.

# Without appending "self"
template.with_address(address) #=> address

# After appending "self"
template.with_address(address) #=> template

This becomes a powerful change to the way we interact with the template object. It enforces the encapsulation of data of the template and it forces us to think more about sending messages to our objects and allowing them to implement the solution.

When we return the object itself, we can only continue operation on that object.

The added benefit is that our code will become more concise. We will prevent unintentional dependencies between objects. And we can chain our commands together; it's all the same object:

template.with_address(address).display_address

See the flow at a glance

By using a visual compass to guide us through our code, it's easy to step back and see exactly where we leave our objects leaking information and responsibility.

Each time we query an object, each time we set a variable, we should now see the westward flow of information.

By simply returning self from our methods, we will force the hand of every developer to think with East-orientation in mind. By only working with the same object we will get back to using objects in the way that tends to be the most useful: for handling messages and implementing the required algorithm.

One last issue is that of the display_address method. Currently it returns the string representation of the address and not the template itself.

We can change that. What you do depends on how you're using a template. Perhaps our base Template will output details to STDOUT, or perhaps to a text file. Here's how we'd take care of that:

class Template
      def display_address
        STDOUT.puts address_lines.join("\n")
        # or perhaps File.write ...
        self
      end
    end

Try this with your code. Return "self" and see how it changes your thinking. Scan for westward flow of information and see how you can push responsibilities into the appropriate objects by heading East.

From now until the end of the year, you can get Clean Ruby for only $42 (the original pre-release price) by using this link. It'll only be valid this year (2014) and will go up automatically in January 2015. Merry Christmas!

Preferring value objects or setters and arguments

The problem with programming can be that there are so many ways to solve a problem. For each solution there are arguments for it and arguments against it.

In recent articles I've written about moving responsibilities into a template object and out of the objects which use them for display.

When the template code first began, its use was extremely simple:

class Address
      def display(template)
        template.display_address(self)
      end
    end

By making changes to the template to allow for shared behavior among different types of templates, the way in which our Address class used it became a bit more complex:

class Address
      def display(template)
        unless protect_privacy?
          template.street = street
          template.apartment = apartment
          template.postal_code = postal_code
        end
        template.city = city
        template.province = province
        template.display_address
      end
    end

Originally the Address class knew of two features of the template, that it had a display_address method, and that the method took a single argument intended to be the address.

After some rework, the template became easier to manage and it became easier to make alternative formats, but the changes burdened the user of the object with the need for more knowledge. The Address objects now also need to know that there are setters for street=, apartment=, postal_code=, city=, and province=. It also needs to be implicitly aware that the template could render incomplete data; we know we aren't required to set nil values for certain attributes.

Getting back to simple

We made good changes for the template, but I want that simple interface back. I want my address to act as a value object instead of needing to keep track of passing so many arguments.

While I want to go back to this:

class Address
      def display(template)
        template.display_address(self)
      end
    end

I need a way to handle the case where we have sensitive data. What about that protect_privacy? method?

Here's what we could do:

class Address
      def display(template)
        if protect_privacy?
          template.display_address(private_version)
        else
          template.display_address(self)
        end
      end

      def private_version
        self.class.new_with_attributes(city: city, province: province)
      end
    end

With this change, the Address can still make a decision about displaying private data and it merely sends that version along to the template. I'm leaving the implementation of new_with_attributes up to imagination, but we'll assume it will set the attributes we've provided on a new instance and return that.

Our template, when last we saw it, looked like this:

class Template
      attr_accessor :province, :postal_code, :city, :street, :apartment

      def province_and_postal_code
        # ... return the combined value or nil
      end

      def city_province_postal_code
        # ... return the combined value or nil
      end

      def address_lines
        [street, apartment, city_province_postal_code].compact
      end

      def display_address
        address_lines.join("\n")
      end
    end

We've been shifting the method signature of display_address from originally accepting an argument, to then not accepting one, to now requiring one. That's generally a bad thing to change since it causes a cascade of changes for any code that uses the particular method. I'd rather not switch back now, so what I can do is provide a way for the template to get the data it needs.

I'm happy to know how to use Forwardable because I can still keep my template code short and sweet. Here's what we can do. First, lets change hte way we interact with the template:

class Address
      def display(template)
        if protect_privacy?
          template.with_address(private_version)
        else
          template.with_address(self)
        end
        template.display_address
      end
    end

Next, we can alter the template by creating the with_address method:

class Template
      def with_address(address)
        @address = address
      end
    end

Then, we can alter the line where we use attr_accessor to instead query for information from the address and use it as our value object:

require 'forwardable'
    class Template
      extend Forwardable
      delegate [:province, :postal_code, :city, :street, :apartment] => :@address  
    end

As long as we provide an object which has all of those required features, our Templates will work just fine.

Here's the final result for our Template:

require 'forwardable'
    class Template
      extend Forwardable
      delegate [:province, :postal_code, :city, :street, :apartment] => :@address

      def with_address(address)
        @address = address
      end

      def province_and_postal_code
        value = [province, postal_code].compact.join(' ')
        if value.empty?
          nil
        else
          value
        end
      end

      def city_province_postal_code
        value = [city, province_and_postal_code].compact.join(', ')
        if value.empty?
          nil
        else
          value
        end
      end

      def address_lines
        [street, apartment, city_province_postal_code].compact
      end

      def display_address
        address_lines.join("\n")
      end
    end

With this change, the Template is still responsibile for only the proper display of data and will handle missing data appropriately. Our Address is responsible for the data itself; it will make decisions about what the data is, and whether or not it should be displayed with a given template.

Managing change using a common interface

In a previous article I showed a way to move display code into a template object to manage missing data. Here's what the basic template code looked like:

class Template
      def display_address(address)
        province_and_postal_code = [address.province, address.postal_code].compact.join(' ')
        province_and_postal_code = nil if province_and_postal_code.empty?

        city_province_postal_code = [address.city, province_and_postal_code].compact.join(', ')
        city_province_postal_code = nil if city_province_postal_code.empty?

        [address.street, city_province_postal_code].compact.join("\n")
      end
    end

That's relatively short and easy to read code for displaying the data for an address object.

But the display_address method contains the entire algorithm for displaying the data and stripping away any missing values. When we needed to add a new format type we created an HtmlTemplate and it contained duplicated code for the display_address. That reeks of a future bug where we might need a change to the algorithm and only remember to change one template type.

If we add new attributes to our address, we'd need to change every template so it could handle the new data. Inheritance is an easy solution for managing the way multiple types can handle the change.

And because we specifically allow for data to be missing, we can treat our template object like a partially applied function. Here's what our main template will have...

We'll need methods to set the values to be used for the display data, methods to handle the removal of missing values from the data to be processed, and finally the display method.

To set the data values, we can use attr_accessor:

class Template
      attr_accessor :province, :postal_code, :city, :street

      def province_and_postal_code
        value = [province, postal_code].compact.join(' ')
        if value.empty?
          nil
        else
          value
        end
      end

      def city_province_postal_code
        value = [city, province_and_postal_code].compact.join(', ')
        if value.empty?
          nil
        else
          value
        end
      end

      def address_lines
        [street, city_province_postal_code].compact
      end

      def display_address
        address_lines.join("\n")
      end
    end

With that change, our additional template types can inherit from our beginning Template class and change the behavior relevant to the needs of its format:

class HtmlTemplate < Template 
      def display_address
        address_lines.join("
") end end

Eventually we'll find that the addresses we need to handle might require a secondary bit of information like an apartment number.

class Template
      # Additional attribute
      attr_accessor :apartment

      # Updated collection of information
      def address_lines
        [street, apartment, city_province_postal_code].compact
      end
    end

The way our Address objects interact with these templates would change, of course, but could allow the Address to make decisions about what may be revealed to the outside world:

class Address
      def display(template)
        unless protect_privacy?
          template.street = street
          template.apartment = apartment
          template.postal_code = postal_code
        end
        template.city = city
        template.province = province
        template.display_address
      end
    end

By creating a standard set of template methods, we can treat our objects containing data separately from the objects which display them. What else could we do now that we've made this distiction? For example, what might a template for an IO stream look like?

Forwarding messages with Tell, Don't Ask

My avid use of Forwardable helps me simplify my code to raise up the important parts. When things still end up too complicated, I can reach for null objects to ease my commands into place.

class Person
      def initialize(address)
        @address = address
      end
      def address
        @address || DefaultAddress.new
      end
    end

As we've seen in this code, any Person object will always have an address, but what I do with that Person or address is what can cause some problems in the future.

Displaying an address can sometimes be a complicated matter.

Asking for too much

In the case of displaying the address for a particular person, we might want certain formatting depending upon the available details.

If we only have a person's city, or just city and state, we'd probably only show that. An easy way is to just check for those attributes on the address:

class Person
      def display_address
        "".tap do |string|
          string << address.street unless address.street.nil?
          string << address.city unless address.city.nil?
          string << address.province unless address.province.nil?
          string << address.postal_code unless address.postal_code.nil?
        end
      end
    end

This is easy, but introduces a problem if the display of the address ever changes. With the above code, we are asking for a lot of information from the address. It would be more flexible to move this into the address itself.

class Person
      def display_address
        address.display
      end
    end

    class Address
      def display
        "".tap do |string|
          string << street unless street.nil?
          string << city unless city.nil?
          string << province unless province.nil?
          string << postal_code unless postal_code.nil?
        end
      end
    end

This simplifies the knowledge we store in the Person class for interacting with an address. Now all we need is to know is that the address has a display method.

As an added benefit, it's far shorter and easier to read.

Being prepared for changes

What happens when we need to output a person's address in both an HTML page and a text-only email? In one case we'll need a simple line break, and in another we'll need HTML formatting such as a <br /> element.

Here's an example:

123 Main Street
Arlington, VA 22222

An updated version of our code which would skip missing data and create our desired output would look like this:

class Address
      def display
        province_and_postal_code = [province, postal_code].compact.join(' ')
        province_and_postal_code = nil if province_and_postal_code.empty?

        city_province_postal_code = [city, province_and_postal_code].compact.join(', ')
        city_province_postal_code = nil if city_province_postal_code.empty?

        [street, city_province_postal_code].compact.join("\n")
      end
    end

With simple text a newline is all we need, but in HTML we'll need to provide a break:

123 Main Street
Arlington, VA 22222

We could add features to our Address class to handle changes like this:

class Address
     def display(line_break)
       # same code as above here ...

       [street, city_province_postal_code].compact.join(line_break)
     end
   end

That seems like a simple change, but in order to use it the Person would need to know what type of line break to provide to the address. This would push the decision for how to display the address far away from the address itself.

Instead, we could keep the information for formatting inside an object whose responsibility is specifically for formatting the information. If we require a new type of format, we would then only need to create an object for that format.

For example, our standard template could handle the data with a newline character.

class Template
      def display_address(address)
        province_and_postal_code = [address.province, address.postal_code].compact.join(' ')
        province_and_postal_code = nil if province_and_postal_code.empty?

        city_province_postal_code = [address.city, province_and_postal_code].compact.join(', ')
        city_province_postal_code = nil if city_province_postal_code.empty?

        [address.street, city_province_postal_code].compact.join("\n")
      end
    end

Then our HTML template could handle the data with proper line breaks for it's format:

class HtmlTemplate
      def display_address(address)
        # same code as above here ...

        [address.street, city_province_postal_code].compact.join("
") end end

We should move the duplicated code to a common location so that each template could share it, but this will do for now.

So how might our Person and Address objects use these templates?

All we'll need to do is change our display_address and display methods to accept a template for the formatting.

class Person
      def display_address(template)
        address.display(template)
      end
    end

    class Address
      def display(template)
        template.display_address(self)
      end
    end

If we add new formats, neither or Person nor our Address class will need to change. There's still more we can do to guard against changes but I'll write more about that next time.

Clean Ruby 1.0 is released!

I'm excited to be able to call Clean Ruby "final".

The compliments to that work have been great. Here's just a few comments I've received for Clean Ruby:

"The current version of Clean Ruby is a great start on a critical topic. Learning how to keep code clear and understandable is useful for any kind of project. I've already applied a couple of ideas from the book to keep a project from mumbling in the shadows."
—David Richards

"I have not come across such a revelatory approach to things since first learning OOP."
—Mike Pence

"Clean Ruby from Jim Gay will change the way you design your Rails apps"
—Hector Sansores

As time goes on, I'll be updating the book with changes to Ruby and new ideas, but it's at a point where you can get some great techniques. Self-publishing this book has been wonderful for handling updates; I'm able to make changes and get them in the hands of my customers as soon as I can. I'm not limited by a publishing house setting my schedule.

My free newsletter has helped me engage with developers from all over the world. I'll be continuing writing there and releasing more useful tools like Casting and Surrounded. I'm eager to try screencasts and more books.

Grab a copy of Clean Ruby and help me celebrate by using the code TAKE10 for $10 off!

Avoiding errors when forwarding to missing objects

The "final" update for Clean Ruby will be released soon. More on that below, but first here are some thoughts on what to do when you've got a missing object.

The Ruby standard library Forwardable is really useful for raising up valuable information and hiding unimportant details.

A single line of code can configure the relationship between two objects and the data they share.

delegate [:street, :city, :state] => :address

I'm often asked: what happens if that address is nil?

In this case, you'll see an error about an undefined method on nil:

NoMethodError: undefined method `street' for nil:NilClass

You might want that, or you might not. It depends on how you want to structure your program.

When using the Forwardable library, the street method above will raise an error if address is missing.

But, it might make the most sense for your application that if there is no address, then there is obviously no street. So a method that handles this will make more sense:

def street
      if address
        address.street
      end
    end

With this requirement, Forwardable seems useless. I don't have a way to configure Forwardable to just skip the nil object and the forwarded message. ActiveSupport (and Rails) adds its own answer to this problem.

delegate :street, :to => :address, :allow_nil => true

By specifying allow_nil the call to street will silently continue returning nothing if the address is nil. This type of approach to managing nil objects is valuable when it's what you want (of course), and can be a life-saver when you're dealing with a large and/or unfamiliar codebase that's throwing up errors where you don't expect them.

A problem with this approach, however, is that the absence of a an object might be an indication that you're missing some vaulable setup steps. Perhaps a missing address is a problem and removing the error hides the problem. You can take your error as encouragement to use a null object, an object which will stand-in for your missing address.

class Person
      def initialize(address)
        @address = address
      end
      def address
        @address || DefaultAddress.new
      end
    end

You likely have a different way to initialize your objects, but with something like the above code we can use a DefaultAddress which can answer for your missing address.

class DefaultAddress
      def street
        "123 Home Base"
      end
    end

By following this design you can easily change your program from displaying nothing, as you do in the case of allow_nil, to displaying a default value. But what's great about this structure is that you can change the default behavior without any change to your Person class.

Before reaching for an option like allow_nil, consider an alternative object instead. How do you handle nil objects in your code?

Lastly, Clean Ruby is out and you can get it now! I'll be keeping the book up to date with relevant changes to Ruby or with any good techniques for Object-oriented programming so "final" true, barring any updates that come along.

Shorter, simpler code with Forwardable

I often find that visual distractions slow me down. Reading simple code with familiar concepts feels cumbersome when I have to sort through repetition to find the meaning.

Take a glance at this code to see what I mean:

class Person
      def street
        address.street
      end

      def city
        address.city
      end

      def state
        address.state
      end
    end

Although the code is short, you have to think a bit before you realize that all of these methods do basically the same thing.

Ruby has a built-in way to bring the information out of this code: Forwardable.

I touched on using Forwardable in a previous article but we'll look closer at what's happening and why you want to use it.

The code above merely forwards the given method to another object. In this case if you try to get address details from a "Person", it will automatically pass it along to the related "address" object.

Given that the procedure is so simple and common in the code, I'd much rather have a way to read that information faster.

require 'forwardable'
    class Person
      extend Forwardable

      delegate [:street, :city, :state] => :address
    end

With this code, the concept of forwarding a message to a collaborating object is so clear that it reads like configuration.

Good configuration is fast and easy to understand.

Forwardable works essentially the same way that the longform code above does. You can provide a list of methods which should be sent to a particular object. Here's what a simplified version of what Forwardable looks like:

module Forwardable
      def delegate(hash)
        hash.each{ |methods, accessor|
          methods.each{ |method|
            instance_eval %{
              def #{method}(*args, &block)
                #{accessor}.__send__(:#{method}, *args, &block)
              end
            }
          }
        }
      end
    end

The "delegate" method accepts a hash where the keys are the method names to forward and the values are the object names to receive the forwarded messages.

For each item in the hash, it will loop through each method name and define a method using instance_eval and the generated string. Those methods send the message along to the object you specified.

The Forwardable code looks complicated, but it's merely 2 loops over a hash and an array, then the instance_eval. The ultimate result is the equivalent of the original code above. With some simple iteration and dynamically defining methods, Forwardable helps us strip away the unimportant parts and raises the valuable information to the top:

delegate [:street, :city, :state] => :address

This shows us what methods will be sent to which object without any additional code to sort through. What could be simpler or easier to scan and understand?

The tools that are right under your nose

I recently had a fantastic experience giving a presentation at RubyConf called The Secrets of the Standard Library. The slides are available and once the video is up I'll send along a link to that.

There are no secrets in the Standard Library

There are no secrets, of course, because the code is right there for you to read but many developers don't realize that powerful tools like SimpleDelegator and Forwardable are built into Ruby. There's no gem to find and install, just require the file you need and you've got it. It's as easy as:

require 'delegate'
class MyWrapper < SimpleDelegator; end

require 'forwardable'
class MyClass
  extend Forwardable
end

My goal in the RubyConf presentation was to show that these tools are available and to describe how they work. Using the tools is one thing, but understanding them is another.

In previous posts we've been looking at ways to use SimpleDelegator to handle presentation behaviors and there's been a bit of Forwardable too. Once you've got a clear understanding of them, you can be more creative with their use and build your own tools to make your code more habitable.

I find that implementing my own library can be a great exercise in understanding an existing one. It was fun to write two short lines in an attempt to create SimpleDelegator and Forwardable in what would fit in less than 140 characters:

# My SimpleDelegator
class D;def initialize(o);@o=o;end;
def method_missing(m, *r, &b);@o.send(m,*r,&b);end;end
# My Forwardable
module Fwd;def fwd(a,m,n=m);self.class_eval
"def #{n}(*r,&b);#{a}.__send__(:#{m},*r,&b);end";end;end

Expanding those out with more descriptive names reveals a bit more about what they do:

# My SimpleDelegator
class Delegator
  def initialize(object)
    @object = object
  end
  def method_missing(method, *args, &block)
    @object.send(method, *args, &block)
  end
end
# My Forwardable
module Forward
  def forward(to, method_name, alternative=method_name)
    self.class_eval "
     def #{alternative}(*args, &block)
       #{to}.__send__(:#{method_name},*args, &block)
     end
    "
  end
end

In both my simple implementation and the actual implementation one uses method_missing at run time and the other defines methods at compile time.

Knowing this, and seeing how they work, can help you make decisions about when to use one over the other. Defined methods are faster than method_missing but they require a more rigid structure.

When do you use SimpleDelegator and when do you use Forwardable?

I generally follow these simple rules for choosing which library to select:

  1. Use SimpleDelegator when you either don't know or don't care which messages may be sent to your object. This excepts (of course) the methods you define in your wrapper.
  2. Use Forwardable when you know the messages to forward ahead of time.

Both libraries follow the same pattern that a message to one object will be sent along unaffected to the relevant object. But there are times when building your own gives you a better understanding and more control over when errors occurr.

Building your own SimpleDelegator can be tricky. There's quite a lot of work done for you already to help ensure that your wrapper acts like the wrapped object so do read the code and get familiar with the trade-offs when writing your own.

Errors instead of method_missing

Sometimes you may want more control or restriction on the behavior of objects.

You can build a wrapper with Forwardable, for example, by swapping out the object of concern and instead of everything passing through method_missing, you'll get a NoMethodError.

Here's a short example:

class Person
  attr_accessor :name, :color, :number, :email
end
require 'forwardable'
class Wrapper
  extend Forwardable
  delegate [:name, :color, :number] => :person

  attr_accessor :person
end
wrapper = Wrapper.new
wrapper.person = person1
wrapper.name #=> person1 name value
wrapper.person = person2
wrapper.name #=> person2 name value
wrapper.email #=> NoMethodError

A wrapper like this allows us to specify only the methods we want to pass-through and any others that person may have will raise an error.

How have you used these libraries? How do you decide what to use?

What have you built to do similar things?

Last but not least, I recently wrote about undestanding delegation on my blog and how it helped me create the casting gem.

If you enjoyed this post, sign-up for my newsletter below and get more.

Delegation is Everything and Inheritance Does Not Exist

Sharing behavior among and between objects requires a balanced decision. Will other objects use this behavior? Which ones? Why? Should I make a new class to handle what I need?

Determining answers led me to dive into exactly what delegation is and inevitably led to more research to get a better understanding of inheritance.

Prefer delegation over inheritance goes the standard advice.

It seems that many developers think about inheritance in terms of classes. Classes define everything about your objects so it must be the only way to handle inheritance. We tend to think about delegation in terms of instances of classes as well.

This mental model mostly works well. But then there's always someone who points out a seemingly contradictory phrase...

Delegation is Inheritance

Lynn Andrea Stein argued that Delegation is Inheritance in her 1987 OOPSLA paper of the same name. It's a fantastic read and an important paper in describing the behavior of Object-oriented systems and what the costs and benefits are to different inheritance schemes.

But this title seems to go against a simple mental model of what inheritance and delegation are.

Classes and Prototypes

First and foremost, object-oriented programs tend to have either class-based or prototype-based inheritance.

Sometimes you'll see comments around the web like this

a problem that Javascript is having is people wanting to force OOP on the language, when fundamentally it’s a prototype-based language

It's certainly a good thing to understand the way a language was designed, but there is no dichotomy between OOP and prototypes.

Prototypes are an object-oriented paradigm.

Classes are a paradigm which groups objects by type. Classes generate instances whose abilities are defined by their class. This is a rigid approach to sharing behavior and is the one provided in Ruby.

Prototypes on the other hand share behavior among individual objects. An object's prototype defines behaviors that may be used on the object itself.

Perhaps a problem that people see in JS development is instead forcing a class-based paradigm on their programs. Perhaps not. I'm not venturing into that debate but recognize that prototypes are OO.

Inheritance Through Delegation

Many (most?) OO programmers are familiar with class-based inheritance systems.

You create a new instance of Thing and that thing instance has all of the abilities defined in its class. This concept is easy to grasp.

Prototype-based inheritance, however, seems much more complex. In order to understand the behavior of one object you also need to understand the behavior provided by its prototype which is just another object. A prototype doesn't necessarily act as an umbrella of classification like classes.

It's harder to think in generalizations outside of a class system. The type of an object is a simple mental model but with prototypes, the possibilities are myriad.

But getting back to the point of this section, class-based inheritance uses delegation to share behavior. A message sent to the instance thing is delegated to the class Thing. All of the behaviors are defined in the class, but self is bound to the object that received the message. The behavior is evaluated in the context of the object. That is: self refers to the instance, not the class (where the behavior is defined).

class Thing
  def hello
    self.inspect
  end
end

thing = Thing.new
thing.hello # <-- delegation to its class which defines the behavior

In a case where two objects exist in a prototype-based system, the same rules apply. The keyword self is bound to the object that received the message and any delegated behavior is defined in another object.

Ruby delegates through classes and as a result caches its methods based upon the classes of objects. This class-based approach means that adding new behavior to an object leads to the cache being cleared because as an instance of a particular class the object's behavior changes and needs to be reflected in the method lookup (defined by its class). Charlie Somerville has a great rundown of things that clear Ruby's method cache.

Our class-colored lenses skew our understanding of delegation.

Inheritance Does Not Exist

This brings me around to why reading Stein's argument about delegation being inheritance is important. Most (or maybe just many) programmers seem to misunderstand what delegation is.

Stein's paper made the argument that delegation is inheritance. Her paper is based upon the definition of delegation citing Henry Lieberman's 1986 paper.

Lynn Stein was recently very helpful to me and suggested that the original understanding of delegation may have come from "Delegation in Message Passing Proceedings of First International Conference on Distributed Systems Huntsville, AL. October 1979". Alas, I can't find that paper online but it is related to the application of the Actor pattern by Carl Hewitt, Beppe Attardi, and Henry Lieberman.

Stein's work was built against the understanding that delegation has a specific meaning. When methods are delegated, they are bound to the object that received the message. The self or this keywords (depending on the language) refer to the original object that received the message.

Many commenters on my delegation article (and on other forums) claimed that the "delegation" term has changed meaning over the years. Lieberman, critics say, may have coined the term but he doesn't own the meaning.

Some have argued that delegation no longer means what Lieberman, Stein, and other OO pioneers meant. If this is true and delegation means 2 objects forwarding messages, and if delegation is inheritance, then effectively every object sending a message is inheritance. Either that or inheritance does not exist.

Why Care?

I've been working around the limitations of implementing DCI in Ruby and the behavior of objects is a central concern.

In DCI our bare data objects gain behavior inside a context relevant to some business goal. Typically this is either explained through the use of extend to add a module to an object's inheritance lookup:

thing.extend(SomeModule)
thing.method_from_module

The problem in Ruby is that the object's inheritance tree remains the same for the life of the object.

# Before
thing.singleton_class.ancestors #=> [Thing, Object, Kernel, BasicObject]
thing.extend(SomeModule)
# After
thing.singleton_class.ancestors #=> [SomeModule, Thing, Object, Kernel, BasicObject]

The thing object is forever tied to it's new set of ancestors. This may affect your program if you expect your object to lose behavior after executing some procedure inside a DCI context.

There are projects which hack Ruby to add unextend or other like methods, but they are additions to Ruby typically only in one interpreter (like MRI).

What Can Ruby Do?

A new feature of Ruby 2.0 is exciting in the abilities we'll have to build libraries that aid in delegation.

Methods defined in modules may now be bound to objects regardless of their class ancestry.

SomeModule.instance_method(:method_from_module).bind(thing).call

That code is a mouthful, but it shows (in Ruby 2.0) that we can add behavior to objects without extending them.

If we want to implement a delegation technique we could hide all this inside a method.

def delegate(method_name, mod)
  mod.instance_method(method_name).bind(self).call
end

This is an approach I built into casting, a gem that helps add behavior to objects, preserves the binding of self inside shared methods and leaves the object in it's original state.

It's easy to use, but it takes a different view of what delegation is compared to how most Ruby developers seem to think. The delegated method here will preserve the self reference to the thing object and behavior is added without extending the object.

class Thing
  include Casting::Client
end

thing.delegate('some_method', SomeModule)

It's a work in progress and has given me a great reason to explore what Ruby can and can't do.

The Best of Both Worlds

Stein's paper suggested that a hybrid system of both class-based and prototype-based inheritance would provide both rigidity and flexibility when needed.

As I've worked with my code more and researched more for Clean Ruby I've had the desire for a hybrid system. Stein's words ring true:

In order to take full advantage of the potential of such a system, objects must be treated simply as objects, rather than as classes or instances.

Indeed, DCI requires a system where an object gains and loses behavior based upon the context. The behaviors are localized to the context and a hybrid system like the one Stein described would benefit from the advancement of DCI.

This is a challenge to implement in Ruby but I'll be working more on casting in the future.

For now, it's useful to consider the contextual behavior of our objects and think less about the classes that define them and more about the message passing among them.

Focus on the behavior of your system first, use delegation and worry about classes later.

How abstractions encourage good thinking

Many times, as developers, we grow our code in ways we don't intend. We live with quick decisions a little too long and end up with a problem where, well, we don't see the problem. With too much of this, our code becomes our unkempt bedroom or messy desk.

Working against your brain

A few years ago I saw an excellent presentation at Rocky Mountain Ruby by Michael Feathers about a phenomenon he called "code blindness." In that keynote he raised the point that despite the fact developers may know how to, or know why our code should be structured differently, we become used to seeing things the way they are and no longer recognize real or potential problems. We become blind to it.

This type of behavior is a result of how our brains react to visual clutter. As we add more information, more objects, and more variablity to the environment we're creating, our brains will dampen the signals from each part and hide their influences on our attention.

The dampening of each stimulus is a way we cope with too much information. The NIH released a news advisory in 1998 which explained how our brains can counterbalance the dampening effect with focused attention. So what exactly does this mean and how does it apply to programming?

Read the NIH advisory here.

Our programming languages are merely ways of representing concepts. Our brains translate characters to representations of things, to describe iteration, to define decisions and outcomes, and more. The more variation and number of concepts we require our brains to translate, the harder it becomes to maintain focused understanding of any individual concept.

This, of course, leads to the development of ideas such as separation of concerns, the single responsibility principle, and others in which we aim to remove visual clutter form our code and reduce the cognitive load on our brains required to translate stimuli into ideas.

By dampening the effect of stimuli, our brains are able to better focus on the immediate task. The studies at the NIH revealed that by placing effort to focus on a particular aspect of our environments we are able to counteract the dampening feature of our brains. This makes quite a bit of sense: pay attention to something and you're more likely to notice it. But as the NIH points out that while we may only partially cancel-out the effects of nearby stimuli, the amount of the attention required increased in tandem with the amount of visual clutter.

Living with complexity and clutter in our code is often a way we decide to get work done faster now and come up with a better solution later. Unfortunately it is also a decision to create an environment where we'll have to work harder in the future to focus on the right thing.

Working with your brain

The more we have in our environments demanding attention, the more our brains will dampen our attention to them.

Abstractions, such as the presenters we've reviewed in previous articles, are a way we can remove visual clutter and unnecessary stimuli. Separating our programs into layers of responsibility is a way of working with our brains to ensure they'll only need to place just enough effort required to maintain focus and understanding of a particular concept.

The act of building these layers in our programs is how we make decisions to work with our brains' ability to manage focus and prevent the dampening effect from slowing down our work.

This introduces to our program our idea of habitable code. What we consider to be a place where our brains will function well will be expressed in our program code. Often, the place I find the most trouble is with view templates. As a result I work to treat these as much as possible like configuration where logic and number of distinct objects are kept to a minimum.

Transformations of data are often a place where confusing details can cause us to filter out valuable concepts from our minds. View templates which contain multiple objects, transformations of data, control structures such as if/else/unless blocks or iteration are a source of clutter.

Visual clutter can appear all over or merely in a single line.

link_to timeslot.in_time_zone(@timezone).strftime("%l:%M%p"), 
      new_profile_appointments_calendar_event_path(@calendar.profile, @calendar, 
      :event_slot_id => event_id, :timezone_name => @timezone.name), 
      :class => "open", rel: 'nofollow'

When we write code we create the environment in which our brains must function and react. Often, we end up creating these cognitive barriers in our view templates like this. Fortunately, we're able to simplify them with techniques like pushing complexity into a presenter layer.

If you review the code sample above, you'll need to spend quite a bit of time, far more than you should, just to understand what will be output.

It's important to make decisions to remove the parts unimportant to us. The abstractions which we create can remove as much information as we decide. Leaving parts for our brains to compose can be a feature:

link_to time_display, new_event_path, class: "open", rel: "nofollow"

Or creating a small footprint to handle a concept at a higher level allows us to remove visual clutter and removes the need to compose parts.

presenter.new_event_link(class: "open", rel: "nofollow")

These sample bits of code show no implementation, but the great thing about programming is that we get to choose. The choices we make might work with our brains or might work against them. We can push away noisy details like which timezone to use for formatting and how how to

Our divide and conquer approach with abstraction layers helps us to filter out noise from signal. Of course, with too much abstraction we may become mired in the noise created by divided ideas but we get to decide and experience what fits best.

Work with your brain and consider what ideas belong in which places. Write the code you wish to have.

Unleash the Secrets of the Standard Library

RubyConf 2013 was a fantastic experience and I was fortunate enough to give a presentation about learning from the tools in the Standard Library. The presentation was recorded and will be online soon.

While the slides alone don't reveal the value from my presentation, I encouraged the audience to read the ruby source and discover what the standard library has to offer. We looked at how delegate.rb and forwardable.rb can help solve problems and how they are implemented. There's plenty of tricks to pick up in there.

I had a great time having a chat on Ruby5 too.

Update:

My presentation was posted by Confreaks:

Easy Metaprogramming For Making Your Code Habitable

In my last message, I wrote about simplifying the code you write by using the Forwardable library. It allows you to represent ideas with succinct code:

delegate [:sanitize, :link_to, :paginate] => :view

In one short line we're able to show that certain messages and any arguments will be forwarded to another object.

The Presenter class we've been working with also has convenient methods created based upon the name of any inherited classes. A UserPresenter will have user and user= methods mapped to __getobj__ and __setobj__ by an easy to follow convention of choosing a name that makes sense.

These are ways that I've found in my own code to make it more habitable for me and my team. With as little effort as possible, we should feel at home understanding and changing behavior of the system.

Make your own shortcuts

I have had projects where data would be displayed to a user but may have come from multiple different sources. A user record might be imported from a third-party system and have data that needs to be updated. Or a person in a system might have one or more public profiles from which we need to choose to display information.

If an updated profile has good information we want to show that, otherwise, we'll show some other imperfect information.

Here's an example of an approach I took recently. I needed a way to specify that my data should first come from a profile and then fallback to the user record if no data was available. This is what it looked like:

class UserPresenter < ::Presenter
  delegate [:profile] => :user
  maybe :full_name, :address, :from => :profile
end

I went with the name maybe but you might find that something else is clearer for you.

Here's how I made it work:

class Presenter < SimpleDelegator
  def self.maybe(*names)
    options = names.last.is_a?(Hash) ? names.pop : {}
    from = options.fetch(:from)
    class_eval names.map{|name|
      %{
        def #{name}
          #{from}.public_send(:#{name}) || __getobj__.public_send(:#{name})
        end
      }
    }.join
  end
end

This creates a maybe class method which looks for a collection of method names and an hash in which it expects to find :from. Next it opens up the class (which would be UserPresenter in this case) with class_eval and defines methods based upon the provided string.

The methods are simple and they are equivalent to something like this:

class UserPresenter < ::Presenter
  def full_name
    profile.full_name || user.full_name
  end
end

Although the full methods are short, using this technique allowed me to simplify the code necessary to handle the concept. Additionally, as I needed, I was able to make changes where a blank, but non-nil value wasn't considered a valid.

Changing the behavior to avoid nil and blank strings was easy:

def #{name}
   value = #{from}.public_send(:#{name})
   (!value.nil? && value != '' && value) || __getobj__.public_send(:#{name})
end

Or if you have ActiveSupport:

def #{name}
   #{from}.public_send(:#{name}).presence  || __getobj__.public_send(:#{name})
end

Beware of indirection

This code made sense in my project, but for yours it might not. If I were to only use this for the full_name and address methods then I'd probably be making my project less habitable. A layer of indirection, especially when woven through metaprogramming, can be a painful stumbling block to understanding the code later. Be careful to think about how or if you need to apply code for a pattern like this.

Get more tips like this by signing up for my newsletter below.

What to code when you know what you want

My last few posts have built up a simple wrapper class that helps to add behavior to an object when we're displaying information to our users.

  1. Ruby delegate.rb Secrets
  2. The easiest way to handle displaying bad data
  3. Simplify your code with your own conventions
  4. Formatting collections of objects with SimpleDelegator
  5. How to make your code imply responsibilities

We've been using SimpleDelegator which uses method_missing to do its magic. But there's another way of forwarding messages with the standard library Forwardable.

In our presenters, we've been wrapping a main object and a view to handle concerns for the display but there are certain features that we don't want to augment with our wrapper. In Rails we have methods like link_to which help us to create links in our display, and in previous code I showed how we used the view reference in our presenters to handle sanitizing content:

class Presenter < SimpleDelegator
  def sanitize(*args)
    @view.sanitize(*args)
  end
end
class UserPresenter < Presenter
  def bio_html
    sanitize(user.bio)
  end
end

This sanitize method highlights an aspect of handling the behavior of our presenters: sometimes we know exactly what we want to happen, other times we don't know or don't care.

Use shortcuts for forwarding when you know what you want

When building my presenters, we knew that we needed to have the view handle sanitization because it was built into the framework. But writing methods every time we wanted to send a message to the view is cumbersome. This is how we made it even easier:

require 'forwardable'
require 'delegate'
class Presenter < SimpleDelegator
  extend Forwardable
  delegate [:sanitize, :link_to, :paginate] => :view
end

With this simple change, we can use all of these specified methods inside our presenters and they'll automatically be handled by the specified object, the view.

When this Presenter class is loaded, these methods (sanitize, link_to, and paginate) will be generated for us. They'll define the named methods and automatically pass along any arguments.

This allows us to create simpler classes without the need to create method definition blocks ourselves and our other methods end up looking like this:

class ProfilePresenter < ::Presenter
  def social_media_link(options={})
    link_to('Tooter', tooter_url, options)
  end
end

The access to link_to is implicit: we expect it to be there already. Implicit behavior can be dangerous in that it requires that anyone working with the code know to expect the behavior. Your development team should be aware of the structure of your presenter classes and understand that these methods will automatically be forwarded to the view. But this is all a part of finding patterns in your code.

Rails-flavored forwarding

If you're using Rails, you don't need to use Forwardable because every class in your program will already have a delegate method defined by ActiveSupport.

The syntax is similarly easy:

require 'delegate'
class Presenter < SimpleDelegator
  delegate :sanitize, :link_to, :paginate, :to => :view
end

Your code will be more succinct when you use shortcuts provided by Forwardable and other libraries. SimpleDelegator allows us to create objects which act as a pass-through filter for behavior. Because of method_missing, we can treat our wrapper like a replacement for another object but with Forwardable, we must specify our intentions when we design the class.

Try it out and let me know how you handle managing behavior among objects in your wrappers. Everyone on my Clean Ruby mailing list gets regular tips like this. Signup below.

How to make your code imply responsibilities

Readablity is an important aspect of creating code that you or others will need to understand later. Because I often need to communicate purpose to other developers, I opt to avoid using if/else blocks of code, particularly in view templates.

For example, some users of a system might have certain details available to them based upon their role or some particular bit of data. Here's how I simplified my views using presenters.

Where you might have something like this in your views

<%= if profile.has_experience? && profile.experience_public? %>
  

Experience: <%= user_profile.experience %>

<% end %>

There is a better way...

Tell objects to execute blocks, let them decide if they really should

I want my views to handle conditional options, but I want the conditions to be clearer than querying for values.

<%= user_profile.full_name %>

<%= user_profile.bio_html %> <% user_profile.with_experience do %>

Experience: <%= user_profile.experience %>

<% end %> <% user_profile.with_hobbies do %>

Hobbies: <%= user_profile.hobbies %>

<% end %>

Here I specify what I want to display when the user profile has details for experience or details for hobbies. The implementation is simple:

class ProfilePresenter < ::Presenter
  def with_experience(&block)
    if profile.has_experience? && profile.experience_public?
      block.call(view)
    end
  end
end

The sample code is contrived, but what this allows me to do is move the details of what having experience means. Presently the code checks if the profile has_experence? and experience_public?.

This could easily be moved into a separate method for use in the view:

class ProfilePresenter < ::Presenter
  def has_public_experience?
    profile.has_experience? && profile.experience_public?
  end
end

The problem with a method like this is that 1) its name is dependent upon the implementation and 2) its intent is different from the intent used in the view.

Make your code imply responsibilites

First, the name merely combines two values. What will happen when requirements change and we need to ensure that the provided experience includes at least 3 years of activity? The meaning of has_public_experience? will change along with its behavior and lead to surprises for developers unfamiliar with these particular details. It will no longer merely be existince of experience allowed for the pubilc.

This leads us to the second problem: the intent of the method is to display features, not query for values. Were we to stick with a query method like has_public_experience? we would end up considering the content inside the view along with the meaning of the method every time we read this code.

By creating a method which accepts a block, our view template implies that the responsibility for determining display is elsewhere: in the presenter. The view will display what is configured, but determining that is upto the object we're showing. Leaving query methods lying around in your views is just asking for the next developer to change the view code to profile.has_public_experience? && profile.has_3_years_experience?, and then the value of your presenter is lost.

The name with_experience helped us force developers to consider where changes should be made. How do you prepare your code for change? How does your team ensure that resposibilities are well-managed?

Readers of my Clean Ruby newsletter get regular tips like this. Sign-up below.

Formatting collections of objects with SimpleDelegator

Here's a quick tip about how I used my presenters to handle a collection of objects.

Previous posts relevant to this are:

  1. Ruby delegate.rb Secrets
  2. The easiest way to handle displaying bad data
  3. Simplify your code with your own conventions

Working with collections of objects

A common problem when displaying data comes when we display collections of objects that contain collections of other objects.

I solved this for myself in a simple way with my existing presenters.

My application needed to display search results from an event management system and we called this the Agenda. Our agenda had sessions, days, and time slots and we needed a way to handle presentation details for all of them.

All of these items needed their own code, but we only needed to work with them together. From the start, we didn't break these presenters out into separate files.

Here's the structure of how we managed our agenda presenters

module AgendaBuilder
  class ResultsPresenter < ::Presenter
  end
  class DayPresenter < ::Presenter
  end
  class TimeSlotPresenter < ::Presenter
  end
  class SessionPresenter < ::Presenter
  end
end

This kept our related details together and kept us focused in one place.

Custom iterators

When in came to using these in our view templates, we didn't want to leak knowledge of the object classes into the views. From the start, a simple approach would be to initialize the presenters where you need them. Here's what it could have looked like in our ERB files:

    <% agenda.sessions.each do |session| %> <% session_presenter = AgendaBuilder::SessionPresenter.new(session, self) %>
  • <%= session_presenter.title %>

    <%= session_presenter.other_view_method %>

  • <% end %>

This is ugly. The view template has knowlegde of the classes used to implement the objects it needs to display. Instead, it would be far easier to read and handle changes if it looked like this:

    <% agenda.each_session do |session| %>
  • <%= session.title %>

    <%= session.other_view_method %>

  • <% end %>

Now that is far easier to grok.

Let's take a look at the code:

class ResultsPresenter < ::Presenter
  def each_session(&block)
    presenter = AgendaBuilder::SessionPresenter.new(nil, view)
    sessions.each do |session|
      presenter.session = session
      block.call(presenter)
    end
  end
end

This creates the each_session method which accepts a block that we use for each session in the collection.

The first part of this method may look strange: we initialize a SessionPresenter wrapping nil and providing the view object.

The presenter requires some object to initialize properly and since we're setting the session object later, we can just use nil as a placeholder. But we do this so that we can avoid creating a new presenter with each iteration of the block.

The alternative would look like this:

class ResultsPresenter < ::Presenter
  def each_session(&block)
    sessions.each do |session|
      presenter = AgendaBuilder::SessionPresenter.new(session, view)
      block.call(presenter)
    end
  end
end

While this would work, there's no need to create a new presenter object each time. Our handy session= method does the trick.

Benefits of custom iterators

Providing our own iteration method gave us the ability to change the behavior as we needed. If we merely rely on an Array with agenda.sessions.each, we're tied to that dependecy.

If we decide we don't need a SessionPresenter at all, we don't need to change our view code, we'd only need to remove that from our each_session method.

Following the pattern

We had this need for custom iterators in several places (sessions, days, and time slots) so we have an established pattern. The next step was to move this to our Presenter class so we didn't have to rewrite the same procedure each time.

The only differences between our iterators were the collection of objects (sessions, days, and time slots) and the class of the presenters needed.

All we really want to write is something like this:

class ResultsPresenter < ::Presenter
  def each_session(&block)
    wrapped_enum(AgendaBuilder::SessionPresenter, sessions, &block)
  end
end

With some minor changes to our procedure, we end up with a base wrapped_enum like this:

class Presenter < SimpleDelegator
  def wrapped_enum(presenter_class, enumerable, &block)
    presenter = presenter_class.new(nil, view)
    enumerable.each do |object|
      presenter.__setobj__(object)
      block.call(presenter)
    end
  end
end

We went back to our SimpleDelegator __setobj__ method to avoid knowledge about the domain of the presenter.

Iterating over and presenting items from our collections became so much easier and our views so much simpler. This allowed us to treat our views more like readable configuration. A title method called in the view template could be the actual title from our wrapped object just passing the data through, or, as we change our requirements, could become anything else without requiring changes to our template.

Our view template captured our intent, whereas our presenter captured the requirements and implementation.

Simplify your code with your own conventions

Finding and automating repeated ideas in your code can be a great way to avoid errors and make yourself feel at home. As you build your own software, you and your team can create a framework that makes implementing new features a breeze. Here's how I implemented some changes that helped us do some serious cleanup.

You may recall from my last post about displaying bad data that my presenter looked a bit like this:

require 'delegate'
class UserPresenter < SimpleDelegator
  alias_method :user, :__getobj__
  def initialize(object, view)
    super(object)
    @view = view
  end
end

That leaves out some a custom method, but you get the picture of how it's created. This wasn't a new gem I pulled in to solve a problem, it was built from scratch.

Once I have something that works and feels comfortable, I end up finding a need for it in different ways. Sure enough, I found that I could use presenters in other places. Classes like ProfilePresenter, ShoppingCartPresenter, and others began to appear.

There are a few things I did to make myself feel at home with them and, better yet, make it easier for others to implement their own.

Let Ruby do the work

I don't want to be recreating this same bit of code when I find a new need for a presenter.

One helpful aspect of my user presenter was the user method I had available. It was a name that expressed the object much better than the standard __getobj__ method. If I needed similar methods in other presenters, I'd rather not be writing alias_method over and over again.

The ProfilePresenter should have a profile method and the ShoppingCartPresenter should have a shopping_cart method, and so on.

So I created a starting point that would do this for me.

I decided that I would stick to a simple naming convention using the class name of my presenter to generate the method accessors.

require 'delegate'
class Presenter < SimpleDelegator
  def self.inherited(klass)
    # get the part of the class name we want like "ShoppingCart"
    base_name = klass.name.split('::').last.sub('Presenter','')
    # downcase and underscore (without activesupport) like "shopping_cart"
    wrapped_object_name = base_name.gsub(/([a-z][A-Z])/){ $1.scan(/./).join('_') }.downcase
    klass.send(:alias_method, wrapped_object_name, :__getobj__)
    klass.send(:alias_method, "#{wrapped_object_name}=", :__setobj__)
  end
end

When any class inherit's from that, it'll automatically alias methods based upon the name of the class. It's equivalent to:

class ShoppingCartPresenter < SimpleDelegator
  alias_method :shopping_cart, :__getobj__
  alias_method :shopping_cart=, :__setobj__
  # more custom methods that we need
end

Instead of all that, however, it just looks like this:

class ShoppingCartPresenter < Presenter
  # more custom methods that we need
end

Displaying potentially dangerous data

My UserPresenter had become useful when we needed to display a bio for a user. Our data could contain HTML and a we needed to be careful about what would be displayed. We certainly didn't want arbitrary scripts being loaded from any bio content.

Given that I had a Rails application, we were able to use the standard sanitize method to clean up HTML content. And now that we've got presenters, it gave us a perfect place to tie our objects and views together so that our template files could be simplified.

Originally, our view looked like this

<%= sanitize @user.bio %>

But we had already made some changes to use a @presenter in another place, so we can lean on that to make our view template simpler.

Our presenter initializes with combination of an object and view, so we can handle this behavior inside:

class UserPresenter < Presenter
  def bio_html
    @view.sanitize(user.bio)
  end
end

Then our view template becomes a bit more predictable when moving over to the @presenter:

<%= @presenter.bio_html %>

If we want to provide this ability to all presenters, we can add the behavior to our base class:

class Presenter < SimpleDelegator
  def sanitize(*args)
    @view.sanitize(*args)
  end
end
class UserPresenter < Presenter
  def bio_html
    sanitize(user.bio)
  end
end

A big benefit there is that we had better control over what created our sanitized html. Our code managed the dependency on the Rails sanitization behavior and if, for any reason, we decided to use an alternate strategy for sanitizing our data, we'd have a single place to look to make the change.

Simplified interfaces

Creating our own conventions made using our code predictable and easy. It gave us sensible expectations for how it would work.

Moving the responsibility for creating a sanitized bit of data from the view template into a presenter object helped us to better manage our templates with simpler code. And it helped us stick to a single interface for data display.

Next time I'll cover how I was able to use wrappers while looping over collections of objects and how we removed if/else statements from our views.

How have you used your own conventions to simplify your process?

The easiest way to handle displaying bad data

I've spent time on a few different projects recently where some simple changes helped to clean up some difficult parts of our code. Here's an easy way to simplify your code.

Displaying the wrong thing

On a recent project there was some existing view code that expected to display a link to a person's profile on another site.

But there was a problem where the link just wasn't working properly. Some profiles properly linked to external sites, but some linked to a bad url.

Jim's profile might have had a link like this: http://other.site.com/profile/123

But Amy's profile had a link like this: http://mycompany.com/dashboard/other.site.com/profile/234

Do you see what's wrong there? The link code was generated like this <a href="other.site.com..."> instead of including the important http:// in it.

The problem was that our database stored either value. While we could change the validation of the data on creation, we'd still need to ensure that existing data was handled properly.

Rather than processing all of our data and updating it, presenters are a perfect solution for this.

Clean up with SimpleDelegator

I wrote about delegate.rb secrets in detail on my blog but here's a quick example of how you can use it right now to clean up some code.

Often Rails apps in particular end up with a lot of logic inside the views and this can quickly grow out of control. One way to simplify this is to create a presenter object which brings together the object you need from your controller and the view.

First, let's change the controller.

Down below, we'll go over how this can help you with more complex code, but let's keep it simple for now. Take any of your basic controllers that look like this:

def show
  @user = User.find(params[:id])
end

Change it to:

def show
  @user = User.find(params[:id])
  @presenter = UserPresenter.new(@user, view_context)
end

That's the first small step, but it gives us a lot more flexability. One thing to note is that view_context method is the controller's reference to the view that it will render. Let's walk through the next step...

Building a Presenter

Make a user_presenter.rb file somewhere in your app directory (app/models is fine, and later you may choose somewhere else but this is fine for now).

require 'delegate'
class UserPresenter < SimpleDelegator
  def initialize(object, view)
    super(object)
    @view = view
  end
end

This creates a SimpleDelegator object which wraps (in this case) the @user from our controller. Since the links we displayed were acting incorrectly, let's solve that.

First, I always want to use method names that make sense to me. SimpleDelegator provides the method __getobj__ to refer to the object that you've wrapped, but it's ugly, and you or others may forget exactly what that means. From the start, I provide an alias for myself:

class UserPresenter < SimpleDelegator
  alias_method :user, :__getobj__
end

Now I can use a method that makes things much clearer. So let's get to the link fixing...

class UserPresenter < SimpleDelegator
  def other_site_link
    if user.other_site_link.match(/\Ahttp:\/\//)
      user.other_site_link
    else
      "http://#{user.other_site_link}"
    end
  end
end

This simple change allows our presenter to handle the case where the "other_site_link" doesn't have the "http://" prefix.

Now I can go to my view and change from @user to @presenter.

After that, it's far easier to test that my presenter displays the correct information and handle when the database doesn't.

Other Benefits

This was a very small example. I've seen many controllers with more than just one instance variable to handle data for the view.

A presenter gives you a single object to handle multiple items for your view. Instead of making a new instance variable, why not make a method on your presenter?

Try it out. Often we wait too long to make a new class to handle some behavior and in the case of our views, the code easily becomes unwieldy.

Stay tuned for more updates about handling code growth and business logic. In the meantime, what difficulty are you overcoming with your code?

Simplifying JS function arguments for recursion with this

In a previous post, you read about how to ensure that a deeply nested object structure exists. We wrote a simple function ensure_struct that takes a string, splits it up, and turns it into a nested object.

In the original function it accepted 2 arguments: the string and an optional scope.

We used the optional scope as a way to aid in recursion. The function grabbed the first part of our string and made sure there was an object with that name, then it took the rest of the string and passed that object in as the scope. Down it went through the object structure until there were no more parts of the string left.

The string flamethrower.fuel.fire became the object {flamethrower:{fuel:{fire:{}}}}.

JS is powerful and leaning on the use of the this keyword instead of passing an optional argument makes the function even simpler. Let's look at the final function:

var ensure_struct = function(attributes) {
        if (attributes == '')
            return this;

        var parts = attributes.split('.');
        var first_part = parts.shift();

        if (typeof this[first_part] === 'undefined')
            this[first_part] = {};

        ensure_struct.call(this[first_part], parts.join('.'));
        return this;
    }

This is mostly the same as last time, but what's different is that we're not checking for a value for scope, the optional argument. Last time we had var scope = scope || this; to check if there was a scope given, or just set it to this.

But we can ignore that entirely because the value of this can be set by using either of 2 core functions in JS.

Instead of calling the function and passing the scope, we can set the value of this by using either call or apply.

It's here where that magic happens:

ensure_struct.call(this[first_part], parts.join('.'));

That line takes the function and uses the call function on it. By using call we can pass an object that we want to be the value of this when the function is run. It's the same as just running the function ensure_struct(parts.join('.'); but telling it to use a specific value for this (which is the last object created in our function).

While we're still recursively applying the function to our objects and strings, we no longer need to track an additional variable.

We can do the same thing with apply but the additional arguments we send must be in an array:

ensure_struct.apply(this[first_part], [parts.join('.')]);

Now we can either call our function and set a nested object on our window (what the value of this would be originally) or we can tell the function to apply a specific value to this.

var ensure_struct = function(attributes) {
        if (attributes == '')
            return this;

        var parts = attributes.split('.');
        var first_part = parts.shift();

        if (typeof this[first_part] === 'undefined')
            this[first_part] = {};

        ensure_struct.call(this[first_part], parts.join('.'));
        return this;
    }

    var some_object = {};
    ensure_struct.call(some_object, 'deeply.nested.structure');