Reading and Writing Arrays to Text Files in Ruby
I wanted to be able to schedule publishing new articles here on a regular schedule. One thing I needed was to create a simple mechanism to tell the publisher which posts are upcoming and the order to publish them in.
I opted for a simple text file called publish_queue
which sits in the Jekyll _drafts
folder, along with the draft posts that are ready to publish and queued up, or under development for future queuing. It will likely be a YAML text file eventually, but a simple file with the name of the draft post on each line seemed a sufficient first solution. So the file looks like:
waterfall-versus-agile-development.adoc
reading-and-writing-to-text-files-in-ruby.adoc
scaling-agile-to-the-enterprise-resources.adoc
I read each line of this file into an array where each array item is the name of a post, and call a method to determine which is the next one to publish (currently the first, but later could be some other rule):
drafts_to_publish = IO.readlines("_drafts/publish_queue").map(&:chomp)
file = next_draft_to_publish(drafts_to_publish)
Since IO.readlines("_drafts/publish_queue")
preserves carriage returns, I call .map(&:chomp)
to strip those off the file names.
After I’ve published the file from _drafts
to _posts
and pushed the changes to the Jekyll repository on GitHub, I need to update the publish queue by calling drafts_to_publish.shift
to remove the draft we just published from the publish queue:
mark_draft_as_published drafts_to_publish
def mark_draft_as_published(drafts_to_publish)
drafts_to_publish.shift
File.open("_drafts/publish_queue", "w+") do |f|
f.puts(drafts_to_publish)
end
end