General_9
General_9

Reputation: 2319

Iterate through files in rails directory, do something with filename?

In my rails project structure I have created a folder pages under the path db/pages . I would like to iterate through all the html.erb files in this db/pages directory and DoSomething with the filename of each of these files. All this should happen when I run rake db:seed so I have placed my code in seeds.rb

Below is my attempted code:

source_path = "/db/pages"

Dir.glob("#{source_path}/*.html.erb").each do |html_page|
  DoSomething html_page
end

This seems to be doing nothing when I run rake db:seed. Where have I gone wrong?

Upvotes: 1

Views: 1936

Answers (1)

PinnyM
PinnyM

Reputation: 35533

Try prepending Rails.root:

Dir.glob("#{Rails.root}#{source_path}/*.html.erb").each do |html_page|

An even more correct approach would be:

source_path = Rails.root.join('db', 'pages')

Dir.glob("#{source_path}/*.html.erb").each do |html_page|

Upvotes: 3

Related Questions