Set Or Append plugin

Plugin details

set_or_append adds a helper method to the Hash class for either setting the value for a key or appending to the current value.

Websitehttp://wiki.pluginaweek.org/Set_or_append Repositoryhttp://svn.pluginaweek.org/trunk/set_or_append Author Aaron Pfeifer Tags hash, append LicenseMIT

Documentation

Install the plugin:
ruby script/plugin install http://svn.pluginaweek.org/trunk/set_or_append

Description
============

set_or_append is useful when you need to keep track of a series of values delimited by spaces (or other character) which are stored in a Hash. It helps DRY the code required to, first, check if a value already is stored in the Hash for a given key and, second, deciding whether to set or a new value or append to the current value.

Usage
=======

set_or_append
-------------------------

For example, suppose you are creating a Hash that represents the properties of an HTML tag. If there are multiple helper methods working independently of each other that add CSS classes to the tag, then the easiest way to add a class to the tag's properties would be like so:

  module MyHelper
    def do_stuff(attributes = {})
      attributes.set_or_append(:class, 'tab')
    end
    
    def do_other_stuff(attributes = {})
      attributes.set_or_append(:class, 'highlighted')
    end
  end


  >> attributes = {:class => 'selected'}
  => {:class => 'selected'}
  >> do_stuff(attributes)
  => {:class => 'selected tab'}
  >> do_other_stuff(attributes)
  => {:class => 'selected tab highlighted'}


set_or_prepend
--------------------

In addition to set_or_append, another helper method called set_or_prepend will do the opposite of set_or_append and prepend new values to the current value in the Hash. Using the same example from above,

  module MyHelper
    def do_stuff(attributes = {})
      attributes.set_or_prepend(:class, 'tab')
    end
    
    def do_other_stuff(attributes = {})
      attributes.set_or_prepend(:class, 'highlighted')
    end
  end


  >> attributes = {:class => 'selected'}
  => {:class => 'selected'}
  >> do_stuff(attributes)
  => {:class => 'tab selected'}
  >> do_other_stuff(attributes)
  => {:class => 'highlighted tab selected'}

Further Documentation

There is currently no advanced documentation for this plugin.

New documentation

Edit plugin | Back in time (1 older version) | Last edited by: obrie572, over 2 years ago