[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Avoiding code repetition - same code but different hashes

aldric[removeme]

2/19/2009 8:57:00 PM

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
1 Answer

Rick DeNatale

2/19/2009 9:13:00 PM

0

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

On Thu, Feb 19, 2009 at 3:55 PM, Aldric Giacomoni <"aldric[remove]"@
trevoke.net> wrote:

> 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.denh...
Twitter: http://twitter.com/Ri...
WWR: http://www.workingwithrails.com/person/9021-ric...
LinkedIn: http://www.linkedin.com/in/ri...