More at rubyonrails.org: Overview | Download | Deploy | Code | Screencasts | Documentation | Ecosystem | Community | Blog

레일즈 어플리케이션 템플릿

어플리케이션 템플릿은 새 레일즈 프로젝트(또는 이미 생성된 레일즈 프로젝트)에 plugin/gems/initializer 등을 추가하기 위한 DSL 을 포함한 간단한 루비 파일들입니다.

이 가이드를 통해서 다음과 같은 것을 익히실 수 있습니다 :

1 사용법

템플릿을 적용하려면, -m 옵션을 이용하여 적용할 템플릿의 위치를 레일즈 제너레이터에 알려줘야 합니다 :

$ rails new blog -m ~/template.rb

URL 을 이용하여 템플릿을 적용하는 것도 가능합니다 :

$ rails new blog -m https://gist.github.com/755496.txt

또한 이미 생성된 레일즈 어플리케이션의 경우, rails:template rake 태스크를 이용할 수 있습니다 :

$ rake rails:template LOCATION=~/template.rb

2 템플릿 API

레일즈 템플릿 API 는 매우 직관적이고 이해하기 쉽습니다. 일반적인 레일즈 템플릿의 예는 다음과 같습니다 :

# template.rb
run "rm public/index.html"
generate(:scaffold, "person name:string")
route "root :to => 'people#index'"
rake("db:migrate")

git :init
git :add => "."
git :commit => "-a -m 'Initial commit'"

다음 절에서는 API 에서 제공하는 주요 메소드의 개요를 설명합니다 :

2.1 gem(name, options = {})

생성된 어플리케이션의 Gemfilegem 항목을 추가합니다.

만약 어플리케이션이 bjnokogiri gem 에 의존하고 있다면 다음과 같이 사용합니다 :

gem "bj"
gem "nokogiri"

이 메소드는 gem 을 설치하지 않는다는 것에 주의하세요. 그렇게 때문에 rake gems:install 태스크를 수행하고 싶을지도 모릅니다 :

rake "gems:install"

그러면 설치가 되지 않은 필요한 젬이 있다면 레일즈가 설치를 합니다.

2.2 add_source(source, options = {})

생성된 어플리케이션의 Gemfile 에 주어진 source 를 추가합니다.

예를들어 만약 “http://code.whytheluckystiff.net” 에서 gem 을 받아오고 싶다면 :

add_source "http://code.whytheluckystiff.net"

2.3 plugin(name, options = {})

생성된 어플리케이션에 플러그인을 설치합니다.

Git 으로부터 플러그인을 설치합니다 :

plugin 'authentication', :git => 'git://github.com/foor/bar.git'

git 서브모듈을 통해 플러그인을 설치하는 것도 가능합니다.

plugin 'authentication', :git => 'git://github.com/foor/bar.git',
                         :submodule => true

서브모듈로 플러그인을 설치하기 전에 git :init 을 해야합니다.

혹은 SVN 을 이용할 수도 있습니다 :

plugin 'usingsvn', :svn => 'svn://example.com/usingsvn/trunk'

2.4 vendor/lib/file/initializer(filename, data = nil, &block)

config/initializer 디렉토리에 initializer 를 추가합니다.

Object#not_nil?Object#not_blank? 를 사용하고 싶다고 가정합시다 :

initializer 'bloatlol.rb', <<-CODE
class Object
  def not_nil?
    !nil?
  end

  def not_blank?
    !blank?
  end
end
CODE

비슷하게 lib()lib/ 디렉토리에 파일을 만들고, vendor()vendor/ 디렉토리에 파일을 만듭니다.

심지어 file() 도 있어서, Rails.root 로 부터의 상대경로에 필요한 디렉토리/파일을 만들 수 있습니다 :

file 'app/components/foo.rb', <<-CODE
class Foo
end
CODE

이렇게 하면 app/components 디렉토리를 만들고 그 안에 foo.rb 를 넣습니다.

2.5 rakefile(filename, data = nil, &block)

lib/tasks 에 주어진 태스크를 포함한 새 rake 파일을 생성합니다 :

rakefile("bootstrap.rake") do
  <<-TASK
    namespace :boot do
      task :strap do
        puts "i like boots!"
      end
    end
  TASK
end

위 코드는 boot:strap rake 태스크를 포함한 lib/tasks/bootstrap.rake 를 생성합니다.

2.6 generate(what, args)

주어진 인자로 레일즈 제너레이터를 실행시킵니다. 예를 들어, 레일즈를 가지고 놀 때마다 발판 코드를 만들기를 원한다면 :

generate(:scaffold, "person", "name:string", "address:text", "age:number")

2.7 run(command)

임의의 명령어를 수행합니다. backtick(`) 과 비슷합니다. public/index.html 파일을 지우길 원한다면 :

run "rm public/index.html"

2.8 rake(command, options = {})

레일즈 어플리케이션의 Rake 태스크를 실행합니다. 데이터베이스를 마이그레이션하고 싶다면 :

rake "db:migrate"

또한 다른 레일즈 환경의 rake 태스크를 실행할 수 있습니다 :

rake "db:migrate", :env => 'production'

sudo 를 사용할 수도 있습니다 :

rake "gems:install", :sudo => true

2.9 route(routing_code)

config/routes.rb 파일에 라우팅 항목을 추가합니다. 아래와 같이 하면, person 발판 코드(scaffold)를 생성하고 public/index.html 도 삭제해 줍니다. 그러면 PeopleController#index 가 어플리케이션의 기본 페이지가 됩니다.

route "root :to => 'person#index'"

2.10 inside(dir)

주어진 디렉토리에서 명령어를 수행할 수 있게 합니다. 예를 들어, 만약 edge rails 의 사본을 새로운 어플리케이션에 복사하고 싶다면, 아래와 같이 합니다:

inside('vendor') do
  run "ln -s ~/commit-rails/rails rails"
end

2.11 ask(question)

ask() 는 사용자로부터 피드백을 받고 템플릿 내에서 사용할 수 있게 합니다. 사용자에게 당신이 추가하고 있는 새로운 라이브러리의 이름을 짓게 하고 싶다면 :

lib_name = ask("What do you want to call the shiny library ?")
lib_name << ".rb" unless lib_name.index(".rb")

lib lib_name, <<-CODE
class Shiny
end
CODE

2.12 yes?(question) 혹은 no?(question)

이 메소드들은 템플릿에서 사용자의 답변에 따른 흐름을 결정할 수 있게 해 줍니다. 만약 사용자가 원할때만 레일즈를 freeze 시키기를 원한다면 :

rake("rails:freeze:gems") if yes?("Freeze rails gems ?")
no?(question) acts just the opposite.

2.13 git(:must => “-a love”)

레일즈 템플릿은 모든 git 명령어를 수행할 수 있습니다.

git :init
git :add => "."
git :commit => "-a -m 'Initial commit'"

3 Changelog

  • April 29, 2009: Initial version by Pratik

Feedback

You're encouraged to help in keeping the quality of this guide.

If you see any typos or factual errors you are confident to patch, please clone docrails and push the change yourself. That branch of Rails has public write access. Commits are still reviewed, but that happens after you've submitted your contribution. docrails is cross-merged with master periodically.

You may also find incomplete content, or stuff that is not up to date. Please do add any missing documentation for master. Check the Ruby on Rails Guides Guidelines for style and conventions.

Issues may also be reported in Github.

And last but not least, any kind of discussion regarding Ruby on Rails documentation is very welcome in the rubyonrails-docs mailing list.