HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

OO coding style in short Ruby scripts

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
scriptsshortstylerubycoding

Problem

I've been using Ruby for about a year now, mostly for small scripts with uses ranging from data munging to DevOps tasks. However, I am not intimately familiar with OOP (I appreciate the functional programming approach I'm often able to take with Ruby) and so I think my code is harder to read and debug than it could be.

I do not think my code is idiomatically Ruby, and I think I'm using a procedural style. I've included a recently-written Ruby script as an example, but at what point should one refactor into a OOP style? Is it always helpful to begin with a OOP structure? And I mean helpful in two senses: the sense that it will be easier for other team members to read the code; and also in the sense that it will make the program more robust and easier to debug.

The script below was intended as a small auditing tool. It takes a CSV (in two possible formats) and compares it to a database, but it has to do a lot of munging and matching because the results are not easily directly comparable.

```
#!/usr/bin/env ruby

require 'csv'
require 'date'
require 'json'
require 'mysql2'
require 'pp'

# Command line argument handling
if ARGV.length "
puts "Outputs JSON of results we do not have in our database"
exit
end

ARGV.each do |arg|
# If the arg is a file that exists...
File.file?(arg) ? @file = arg : @user = arg
end

def redacted?(filename)
/redacted/.match(filename)
end

def make_redacted(csv)
header = csv.slice!(0).map {|x| x.split.join.downcase.gsub(/\(\$\)/, '').to_sym}
fd_csv = csv.map {|row| Hash[header.zip(row)]}
fd_csv.map do |row|
row[:name] = row[:title]
row[:hashtag] = row[:sport]
row[:opponent_score] = row[:oppscore]
row[:place_finished] = row[:position].to_i
row[:prize] = row[:winnings].to_f
row[:date] = Date.parse(row[:date]).strftime('%Y-%m-%d')
#row[:opponent_name] = row[:opponent]
row[:score] = row[:score].to_f
row[:entrants] = row[:entries].to_i
row[:buy_in] = row[:entry].to_f
row.delete_if {

Solution

Never use OOP just because people say it's cool. If you do not know how to apply it, that means you just do not need it in this task. That's it. Forget about OOP. Involving it without much need only makes code worse and unreadable.

Context

StackExchange Code Review Q#94798, answer score: 3

Revisions (0)

No revisions yet.