I am confused about modules and scope.
Here is a module:
module Crumbs
MAX_CRUMBS = 10
def self.included(mod)
def cookies
return @cookies == nil ? Hash.new : @cookies
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
puts cbs.class
cbs = cbs[:rdf_crumbs]
if cbs == nil
puts "crumb_add::cbs is nil!"
cbs =[bite]
else
puts "crumb_add::cbs is OK!"
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
}
puts cookies.class
cookies[:rdf_crumbs] = cr
end
def get_crumbs()
crs = @cookies["rdf_crumbs"]
if crs == nil
return []
else
return crs.split("|")
end
end
end
···
==================================
Here is a unit test:
class Bread
include Crumbs
def initialize
@cookies = Hash.new
end
end
class CrumbTest < Test::Unit::TestCase
attr :bread
def setup
@bread = Bread.new
end
def test_crumbs_simple
@params = Hash.new
bite =bread.crumb_new( "test1", "test_action", @params )
bread.crumb_add(bite)
puts bite
bite =bread.crumb_new( "test2", "test_action_2", @params )
bread.crumb_add(bite)
puts bite
bite =bread.crumb_new( "test3", "test_action_3", @params )
bread.crumb_add(bite)
puts bite
assert bite == "test3^test_action_3"
bites =bread.get_crumbs()
puts bites.class
assert_equal bites.length, 3
end
end
Here is the output:
------------------------------------------
test cookies! on Bread
Hash
crumb_add::cbs is nil!
sets Hash with test1^test_action
has 1
test1^test_action
Hash
crumb_add::cbs is nil!
sets Hash with test2^test_action_2
has 1
test2^test_action_2
Hash
crumb_add::cbs is nil!
sets Hash with test3^test_action_3
has 1
test3^test_action_3
------------------------------------------
And:
------------------------------------------
Test::Unit::AssertionFailedError: <1> expected but was <3>.
test/unit/crumbs_test.rb:62:in `test_crumbs_simple'
------------------------------------------
I have tried different ways, but can't get the Correct Way to have a module
insert a variable into the Class that includes it. In this case it should
inject a @cookies hash, but in tests @cookies always gets reset to
Hash.new...
Excuse the inconsistencies in the code (towards @cookies) b/c I can't seem
to figure out the proper way.
So how do you add instance vars to a class from a module and how to
reference that attribute? Or is this not the Right Ruby Way?
I have a lot of confusion about modules... suppose its my java funk
Please point me to any more docs on modules besides the ruby-lang snippet.
-netcam