lcharbon
lcharbon

Reputation: 3298

Ruby Best Practice For Storing Collection of Procs

I am writing regressive test for my app and I use the class Page. Each page has a nav_to method that needs to be set with a proc when the instance is initialized.

I currently have a list of 40 some procs in the global scope and to me this seems sloppy. What would be the best practice for storing these procs? Should I store them in a module? Hash? Class? Please help!

Upvotes: 1

Views: 204

Answers (1)

maerics
maerics

Reputation: 156434

Consider storing them in a module- (or class-)constant so that they can be grouped and named clearly. The data structure you choose (array vs hash) probably depends most on your desired interface (are they associated with some key or simply ordered?) and performance concerns, if relevant:

module MyTests # ...or "class"

  NAV_TO_PROCS = [
    Proc.new { ... },
    Proc.new { ... },
  ]

  # ... or ...

  NAV_TO_BY_PAGE_NAME = {
    "page1" => Proc.new { ... },
    "page2" => Proc.new { ... },
  }

end

As an aside, when using module constants as such I like to "freeze" them to avoid accidental mutation during use (e.g. NAV_TO_PROCS = [...].freeze).

Upvotes: 2

Related Questions