Some pieces of Ruby code

Among thousands lines of code are some I find particularly useful. They aren't complicated. There are often "obvious" when you have seen them.

A positive integer < 10000 always written with 4 digits

The name of our files are always of the form "SomethingXXXX" where XXXX is the episode number. For episode 4 we have "Something0004".

The simple line of code is:


Truncate a discussion after someone has finished talking

In the text file we separate people talking by "- ". This sequence can't happen in a sentence in French. Let's say we want to keep at least the first 1,000 characters then cut at the next "- ".

The little trick here is to start by taking out the first 1,000 characters instead of trying to find all the positions of "- "

def truncate_episode_text(text)
  base_index = 1000
  text_for_measure = text.slice(base_index..(text.length)-1)
  position_to_trunc = base_index+text_for_measure.index("- ")
  newtext = truncate(text, length: position_to_trunc, :omission => '')
  return newtext

Easy way to export data to csv

First I tried to export csv data from scratch. A library exists to help us! Here we export user data in just a few easy lines.

def self.transform_to_csv
  CSV.generate do |csv|
    csv << column_names
    all.each do |user|
      csv << user.attributes.values_at(*column_names)

Which in my Rails application I call through:

format.csv { render text: @allusers.transform_to_csv }

Destroy all elements of a table

I admit I first tried to get the id of the elements and then destroy these elements using their id. Actually there is something shorter using the each iterator.

Notification.all.each {|n| n.destroy}