syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me

Question:
In Ruby how do I build a loop from a directory full of files?
Tags: ruby dir loop files

Recently I encountered a use-case where I wanted to look inside all the files in a directory.

For each file I wanted to create a second file which contained some enhanced content.

A script which does this task has two parts.

The first part uses a Ruby class named Dir which can transform a directory into an enumerable object.

An enumerable object in Ruby fits well with looping scenarios.

The second part captures the enhancements and then writes them to the target file.

The syntax below demonstrates how to build a loop from a directory full of files:
# ~/x611/script/dirposts2haml.rb

# I use this script to copy filenames from 
# app/views/posts into app/views/posts/index.haml

require 'tempfile'

tfh = Tempfile.new('tmp.haml')

filenames = Dir["#{Rails.root}/app/views/posts/*.haml"]

names_sorted_bydate = filenames.sort_by {|filename| File.mtime(filename) }

names_sorted_bydate.each{ |fn|
  # I should get anchor content
  acont = fn.sub(/\/.*posts\//,'').sub(/.haml$/,'')
  # I should create a link if filename starts with a through z.
  if acont =~ /^[a-z]/
    hrefp = "/posts/#{acont}"
    mydate = File.mtime(fn)
    tfh.puts "%a(href='#{hrefp}') #{mydate.strftime('%Y-%m-%d')} | #{acont}"
  end
}

tfh.close
FileUtils.mv(tfh.path, "#{Rails.root}/app/views/posts/_index.haml")
Ruby gives me the ability to feed a set files into a loop which I can use to systematically enhance the input.

This is a useful feature which addresses a wide range of use-cases.

syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me