Connect With Us

Application Template in Rails

By Kuber Aaganja on Nov, 15, 2016 in application template, rails

While starting any new project, we have to install different gems, generate the root controller and set the default routes, initialize the git, add some files to gitignore and lots of other stuffs. You might have questions whose answers would ease you the problem we just discussed. Well, I had some and here are the answers.

Won’t it be great if these all could be setup while creating new application?
Do you think it is possible to generate everything while creating new application?
Yes, of course, it is.

So what do you think that made it possible?
Well, one of the ways is “Rails Application Template”.

Ok, great! Then, what’s “Rails Application Template”?
The Rails official site defines “Rails Application Template” as ‘Application templates are simple Ruby files containing DSL for adding gems/initializers etc. to your freshly created Rails project or an existing Rails project.’

Now, how to use the ‘Rails application Template’?
It is simple. What you need to do is, provide the Rails generator with the location of the template you wish to apply using the -m option. This can either be a path to a file or a URL.
i.e.

$ rails new app_name -m path_to_template_file/template.rb

OR

$ rails new app_name -m http://url_of_template_file

Example:

$ rails new app_name -m https://raw.githubusercontent.com/aaganja/app_template/master/app_template.rb

Since, the template is run in the context of application generator, we will have access to all rails generator actions, including thor at this template.

Sample of the template.rb

remove_file "README.rdoc"
create_file "README.md",  "TODO"
gem 'pry-rails', group: [:test, :development]
run "bundle install"


if yes? "Do you want to generate root controller? yes/no"
  name = ask("what should be its name?").underscore
  generate :controller, "#{name} index"
  route "root to: '#{name}\#index'"
end


git :init
append_file ".gitignore", "config/database.yml"
run "cp config/database.yml config/example_database.yml"
git add: '.', commit: "-m 'initial commit'"

Advantages using rails application template

  • Ability to mix and match templates
  • Dependencies stay up-to-date
  • Default settings or custom settings in multiple project can be reuse
  • Huge time saving in getting a project started

 

Share This:

Comments


Add a new comment

Latest Posts


Jyaasa in IT Career Fair 2018 By Sonika Thapa on Jun, 12, 2018

Encrypted secrets in Ruby on Rails By Rasna Shakya on Apr, 20, 2018

Rails Payment Integration with zipPay (Buy Now and Pay Later) By Nelson Suwal on Mar, 23, 2018

Getting started with React Native: Core Architecture of React Native By Aman Maharjan on Dec, 15, 2017

First Step to Software Development: Design Thinking Process By Rasna Shakya on Nov, 03, 2017