All threads / How do I learn to write dry code?

Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do I learn to write dry code?

Alisha Taylor asked in Ruby

I've been learning RoR for a year now and have a basic functioning site that people actually use, but my code is not even close to dry... it's probably wetter than the Amazon! Once you have the basics, where can you go to learn not just how to code, but how to code better? I'm open to any advice, suggestions, etc. I am trying to look for a mentor but just getting scammed...

Here is an example from my application controller for code that is used in multiple places on my site (would love suggestions on refactoring this):
def export_tips
@appointments = Appointment.order('service_id')
send_data @appointments.to_csv_tips, filename: 'tips.csv'
end

def export_ticketpayments
@appointments = Appointment.order('service_id')
send_data @appointments.to_csv_ticketpayments, filename: 'ticketspaymentitems.csv'
end

def export_batchmanifest
@batchmanifests = Batchmanifest.all
send_data @batchmanifests.to_csv_batchmanifest, filename: "batch_manifest-#{Date.today}.csv"
end

def export_pets
@clients = Client.all
send_data @clients.to_csv_pets, filename: 'pets.csv'
end

def export_clients
@clients = Client.all
send_data @clients.to_csv_clients, filename: 'clients.csv'
end

In Order to become an overall better software developer, I recommend you read "Clean Code" by Robert C. Martin. I have been developing software for a little more than 2 years now and this book has helped me better understanding what makes good code. Though, if I remember correctly, the code examples are presented in Java, I think you'll get the hang of it just fine.

As for your code example: the overarching pattern seems to be that you export .csv-files in all of these export-controller-methods. You could think about creating some sort of helper-method / controller-concern to which you can pass the data to be exported and the desired output-filename.

def export_csv(data, filename)
  # return unless data.any? you could put a guard-clause here, to prevent passing empty data to the export

  send_data data.to_csv, filename: "#{filename}.csv"
end

You could then do:

def export_tips
  @appointments = Appointment.order('service_id')
  export_csv(@appointments, 'tips')
end

def export_pets
  @clients = Client.all
  export_csv(@clients , 'pets')
end
Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 52,026+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2021 GoRails, LLC. All rights reserved.