[Rails] Rake Task 사용하기 - Who Is Bluesh55?

Rake는 Ruby 개발 환경에서 사용되는 빌드 프로그램이다. Unix에서 사용되는 Make와 비슷한 용도로 사용되며 Makefile과 비슷한 Rakefile이 존재한다.

Rake를 통해 실행되는 작업을 태스크(task)라고 하며 태스크들은 레일즈 서버의 실행여부와 상관 없이 단독으로 실행된다. 레일즈를 설치하면 Rake 젬도 같이 설치되어서 바로 Rake 커맨드를 사용할 수 있다.

레일즈로 개발해봤다면 rake 명령어를 써 본 경험이 있을텐데, 가장 익숙한 명령어는 rake db:migrate 또는 rake routes일 것이다. 이것들은 레일즈에 기본으로 탑재되어 있는 태스크다.

실행할 수 있는 태스크 목록은 rake -T 또는 rake --tasks를 실행하면 볼 수 있다.

Task 만들기

기본적으로 제공하는 태스크 뿐만 아니라 원하는 태스크를 생성하고 실행시킬 수 있다. lib/tasks/my_task.rake 파일을 생성해서 첫 번째 태스크를 작성해보자.

# lib/tasks/my_task.rake task :random_fruit do puts ["Apple", "Banana", "Orange", "Kiwi"].sample end

파일을 저장하고 rake random_fruit 명령을 입력하면 랜덤으로 과일 이름이 출력되는 것을 볼 수 있다.

이번에는 첫 번째와 마지막 과일을 출력해주는 태스크를 만들어 보자.

# lib/tasks/my_task.rake arr = ["Apple", "Banana", "Orange", "Kiwi"] task :random_fruit do puts arr.sample end task :first_fruit do puts arr.first end task :last_fruit do puts arr.last end

실행 결과는 다음과 같다.

이렇게 비슷한 태스크들은 네임스페이스로 묶을 수 있다.

arr = ["Apple", "Banana", "Orange", "Kiwi"] namespace :fruit do task :random do puts arr.sample end task :first do puts arr.first end task :last do puts arr.last end end

실행 결과는 다음과 같다.

지금까지는 간단한 루비 코드로 태스크를 생성했는데 좀 더 복잡하게 레일즈 프로젝트의 실행 환경과 연동시킬 수도 있다. 다음 코드는 과일 목록으로 String array가 아닌 데이터베이스에 저장된 Fruit 모델을 사용하는 예제이다.

namespace :fruit do task :random => :environment do puts Fruit.all.sample.name end task :first => :environment do puts Fruit.first.name end task :last => :environment do puts Fruit.last.name end end

코드의 재사용성을 높이기 위해 자주 사용되는 코드를 메서드로 분리시킬 수 있다. 다음 예제는 중복 코드를 없애지는 않지만 메서드 사용을 보여주기 위해 작성했다.

namespace :fruit do task :random => :environment do puts random_fruit end task :first => :environment do puts first_fruit end task :last => :environment do puts last_fruit end def random_fruit Fruit.all.sample.name end def first_fruit Fruit.all.first.name end def last_fruit Fruit.all.last.name end end

마지막으로, 정의된 모든 태스크 목록을 보기 위해 rake -T 명령어를 사용했었는데 다시 한번 명령어를 입력해보면 위에서 정의한 태스크는 목록에 나오지 않는 것을 볼 수 있다. 태스크 목록에 커스텀 태스크가 나오게 하기 위해서는 태스크 상단에 Description을 입력해주면 된다.

namespace :fruit do desc "Pick a item randomly" task :random => :environment do puts random_fruit end desc "Pick the first item" task :first => :environment do puts first_fruit end desc "Pick the last item" task :last => :environment do puts last_fruit end def random_fruit Fruit.all.sample.name end def first_fruit Fruit.all.first.name end def last_fruit Fruit.all.last.name end end

Tag » What Is Rake In Ruby