Avoiding code repetition - same code but different hashes

A

Aldric Giacomoni

This is probably a wonderful situation for metaprogramming, aka create
the function you need when you need it. I just don't know enough to do
it yet.

I'm going through some logs, and depending on whether the file I'm
looking at is in a subfolder of 'accessed' or 'denied', I'll be adding
information to the hash 'denied' or the hash 'accessed'.
Before we go any further, is this already making life overly
complicated, and is there a better way of doing it?

Otherwise.. How can I avoid code repetition?

Thanks,

--Aldric
 
R

Rick DeNatale

[Note: parts of this message were removed to make it a legal post.]

This is probably a wonderful situation for metaprogramming, aka create the
function you need when you need it. I just don't know enough to do it yet.

I'm going through some logs, and depending on whether the file I'm looking
at is in a subfolder of 'accessed' or 'denied', I'll be adding information
to the hash 'denied' or the hash 'accessed'.
Before we go any further, is this already making life overly complicated,
and is there a better way of doing it?

Otherwise.. How can I avoid code repetition?

Here's a simpler approach than metaprograming

Put the code which computes the information into a separate method, and pass
the hash you want to populate:

def process_file(file, collection_hash)
computed_info = #whatever processing
collection_hash[file.name] = computed_info
end

accessed_hash = {}
denied_hash = {}
Dir.glob("/var/log/accessed/*.log").each {|file|
process_file(accessed_hash)}
Dir.glob("/var/log/denied/*.log").each {|file| process_file(denied_hash)}

There are others.

--
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top