Search code examples
rubycopyfileutilsmaid

How do I copy specific file types with Maid?


I'm a first time Ruby user (any programming code for that matter) and I'm trying to create a script within "maid" to copy all of my music from a specific folder into the "automatically add to itunes" folder:

rule 'Move Downloaded Music to iTunes' do
    FileUtils.cp_r '/Users/*********/Movies/*********/Music/.',
    '/Users/*********/Music/iTunes/iTunes Media/Automatically Add to iTunes/',
    :remove_destination => true
  end

However, I have non-music files within that same folder and I want to include only files with audio formats (mp3, m4a, etc.)

How can I append this code so that I can choose which file types are copied?

Additionally, what is the difference between cp_r and cp?

Any advice or improvements to my code are more than welcome - I've seen people try to do similar things with much more complicated code, so in a sense I'm worried mine is too simple...Thanks for the help!!


Solution

  • Maid provides some helper methods that would assist with this. Let's piece them together, individually.

    # Find all files in your Downloads
    dir('~/Downloads/*')
    
    # Find **any kind of audio files** in your Downloads
    where_content_type(dir('~/Downloads/*'), 'audio')
    
    # Copy these specific MP3 files in Downloads to a specific iTunes folder
    copy(['~/Downloads/song_1.mp3', '~/Downloads/song_2.mp3'],
         '~/Music/iTunes/iTunes Media/Automatically Add to iTunes/')
    
    # Copy any MP3 files in Downloads to a specific iTunes folder
    copy(dir('~/Downloads/*.mp3'),
         '~/Music/iTunes/iTunes Media/Automatically Add to iTunes/')
    

    We can put those pieces together for the full intent, namely copying audio files to the "Automatically Add to iTunes" folder.

    Maid.rules do
      rule 'copy audio files to the "Automatically Add to iTunes" folder' do
        copy(where_content_type(dir('~/Downloads/*'), 'audio'),
           '~/Music/iTunes/iTunes Media/Automatically Add to iTunes/')
      end
    end
    

    If you'd like, this can be broken down using variables -- it's Ruby after all.

    Maid.rules do
      rule 'copy audio files to the "Automatically Add to iTunes" folder' do
        files_in_downloads = dir('~/Downloads/*')
        audio_files_in_downloads = where_content_type(files_in_downloads, 'audio')
        automatically_add_to_itunes_folder = '~/Music/iTunes/iTunes Media/Automatically Add to iTunes/'
    
        copy(audio_files_in_downloads, automatically_add_to_itunes_folder)
      end
    end
    

    I hope this helps!