Description:
I created a class called MenuLink so I could create link objects for my
navigation menus. I want to instantiate the list and have it available
to all controllers in my applcation.
How I did it:
I created a file called menu_link.rb in app/models that contained
class MenuLink
include Enumerable
attr_accessor :name, :method
@@items = []
def initialize()
@@items.push(self)
end
def self.each(&block)
@@items.each(&block)
end
end
Then in my app/controllers/application.rb I put
before_filter :config_defaults
def config_defaults
# More on this function later
MenuLink.reset
###################
MenuLink.new('HOME','welcome')
MenuLink.new('ABOUT US', 'about')
MenuLink.new('SCHEDULE', 'schedule')
MenuLink.new('YOGA INFO', 'info')
MenuLink.new('PHOTO GALLERY', 'gallery')
MenuLink.new('TEACHER TRAINING', 'training')
MenuLink.new('CONTACT US', 'contact')
end
Then in my templates I can do things like MenuLink.each {do stuff}
Now this seems to work alright…except for one thing.
Every time you refresh the page, any page, it creates a whole new set
of MenuLink objects and appends them to the total @@items list.
So I made a reset function for MenuLink
def self.reset
@@items = []
end
So what I’m wondering is:
-
Is there a more correct way to handle this? Perhaps a filter that
only executes a single time and not with every refresh? -
In ruby, is this the correct way to ‘destroy’ objects?