Question: Getting and displaying all files in a folder as links on the home page of my sinatra app

Question

Getting and displaying all files in a folder as links on the home page of my sinatra app

Answers 1
Added at 2017-01-04 23:01
Tags
Question

I'm making a wiki in Sinatra and I have the following code, which works, it just strikes me as a little bit clunky. I'm trying to get all the wiki entries saved in "pages" and display them on the homepage as links.

get "/" do
  @entries = Dir["pages/*.txt"]
  @entries.map! { |f| f.split '/' }
  @entries.flatten!
  @entries.delete_if { |p| p == "pages" }
  @entries = @entries.sample(5)
  erb :welcome, layout: :page
end

If any ruby genius would like to demonstrate eloquent ruby I would be very grateful!

Answers
nr: #1 dodano: 2017-01-05 00:01
  @entries = Dir["pages/*.txt"].
               map { |path| path.split '/' }.
               flatten.
               reject { |path| path == 'pages' }.
               sample(5)

The most obvious thing is to chain method calls. Doing this also leads to a more "functional programming" style. Note how I replaced delete_if (which mutates the array) with reject (which doesn't). I also removed the "bang" methods because using mutating methods is unnecessary here. These shouldn't be the first thing you reach for, because they can sometimes have unintended effects.

For example I recently found a co-worker had written return string.gsub!(" ", "") or something like that. The problem is gsub! returns nil. Using gsub instead worked.

Source Show
◀ Wstecz