jOhn
1/10/2006 9:46:00 PM
Ok here is the final version...
Unit Test:
===============================
class Bread
include Crumbs
def cookies
@cookies ||= Hash.new
end
def initialize
@cookies = Hash.new
end
end
class CrumbTest < Test::Unit::TestCase
attr :bread
def setup
@bread = Bread.new
end
# Simple add/delete/clear tests
def test_crumbs_simples
@params = Hash.new
bite =bread.crumb_new( "test1", "test_action", @params )
bread.crumb_add(bite)
bite =bread.crumb_new( "test2", "test_action_2", @params )
bread.crumb_add(bite)
bite =bread.crumb_new( "test3", "test_action_3", @params )
bread.crumb_add(bite)
assert bite == "test3^test_action_3"
bites =bread.get_crumbs()
assert_equal bites.length, 3
bread.crumbs_clear()
bites =bread.get_crumbs()
assert_equal bites.length, 0
bite =bread.crumb_new( "test1", "test_action", @params )
bread.crumb_add(bite)
bread.crumb_del(bite)
bites =bread.get_crumbs()
assert_equal bites.length, 0
end
def test_crumbs_params
bite =bread.crumb_new( "test1", "test_action",
{"filter"=>"s`divx:divx"})
bread.crumb_add(bite)
bites =bread.get_crumbs()
assert_equal bites[0], bite
end
end
And the crumbs module:
===============================
module Crumbs
#----------------------------------------
#--------------begin/ cookie crumbs mixin
#----------------------------------------
MAX_CRUMBS = 10
public
def crumbs_clear
if cookies != nil and cookies[:rdf_crumbs] != nil
cookies.delete :rdf_crumbs
end
end
def crumb_new( controller, action, params )
cstr = controller + "^" + action
if params != nil && params.keys != nil
params.keys.each {|p|
if params[p] != nil
cstr << "^" << p << "^" << params[p]
end
}
end
return cstr
end
def crumb_add( bite )
cbs = cookies[:rdf_crumbs]
if (cbs == nil or cbs == "") or (cbs.instance_of? Array and cbslength==0)
cbs =[bite]
else
cbs = cbs.split("|")
#don't add a redundant
if cbs.last == bite
return
end
# add to
cbs << bite
# cap the cookie queue at 5 using fifo
if cbs.length > MAX_CRUMBS
cbs.delete_at(0)
end
end
crumbs_set( cbs )
end
def crumbs_set( mouthful )
cr = ""
mouthful.each { |m|
if cr == ""
cr = m
else
cr << "|" << m
end
}
cookies[:rdf_crumbs]=cr
end
def crumb_del( bite )
crs = cookies[:rdf_crumbs]
if crs != nil
crs = crs.split("|")
c2 =""
crs.each { |c|
if c != bite
if c2 == ""
c2 = c
else
c2 << "|" << c
end
end
}
cookies[:rdf_crumbs] =c2
end
end
def get_crumbs()
crs = cookies[:rdf_crumbs]
if crs == nil
return []
else
return crs.split("|")
end
end
#----------------------------------------
#--------------end/ cookie crumbs mixin
#----------------------------------------
end