开发者

How can I automate loading data in a rake file

I have a rake task that populates a database with values.

Here is a sample:

Icon.create!(  :category_id => category_id,
               :name => "Wink",
               :url => "#{url}wink.png",
               :icon_for => icon_for )

What 开发者_开发百科I would like to do is automate this as the 'name' attribute is just the name of the file in a folder but Upper case and without ending while the 'url' attribute is just the file name.

The rest I control with variables.

Is there a way I could something like the this:

  1. read the number of files in a specified folder
  2. loop that number of times and create the object inserting the values for the file names where required.

How can I do this?

Thank you in advance.

Rails 3.0.7 Ruby 1.9.2 Mac OSX 10.6


Yes, you do that with the help of Ruby's standard libraries. You should learn about the File class and the Dir class. Here's a sketch of what your code could look like:

(Dir.entries("path/to/specified/folder") - ['.','..']).each do |filename|
  Icon.create!(:category_id => category_id,
               :name => filename,
               :url => url + filename,
               :icon_for => icon_for)
end

I'll leave it as an excercise for you to figure out how to capitalize the first letter of the filename and chomp off the extension.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜