Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Jonathan Fernandes
PLUS
Jonathan Fernandes
Courses Plus Student 22,784 Points

Rails generators

Hi everyone!

I am looking to add a generator to my projects so that I can speed up the process of some initial work whenever I start a new app.

The problem is when I create a generator, by running:

$ rails generate generator [name of new generator]

it creates it locally on that specific project. Where do I put these files in order to have it accessible to all my rails projects.

I am using a mac with rvm. Any thoughts on where to put the created generator so it can be used across all my projects?

What is the command you would use to then run that generator?

Jonathan Fernandes
Jonathan Fernandes
Courses Plus Student 22,784 Points

Im not looking for the command to run the generator, I'm looking for where to put my new generator files so that when I access any of my rails projects locally, I can access them for all my projects. Right now when I generate a generator, it automatically saves it within that one project. I want to create generators with layouts I can add to all my projects.

Jonathan Fernandes I know, but I need to know this in order to come up with a solution. I have an idea but I need to know how a created generator is subsequently run in order to know if my solution would work. If you could provide a step by step example that would be best.

Jonathan Fernandes
Jonathan Fernandes
Courses Plus Student 22,784 Points

Oh, hahaha, I'm sorry. I misunderstood. Despite that, there really isn't many steps to go through. The way I have created my previous generators is with the following steps:

First I create the app:

$ rails new app

Then I move into it:

$ cd app/

Then I run the generator command to create a generator:

$ rails generate generator app_layout

This creates the generator in the lib/generator directory in which you can edit it. And that's it... Sorry if you were expecting more but that really is all there is to it.

Yes, but how do you then use the generator in the command line?

Jonathan Fernandes
Jonathan Fernandes
Courses Plus Student 22,784 Points

Oh you don't. You can create it in the command line put you edit it in the text editor using the thor language.

Ok I'm confused now! What's the point of making something you can't use? What does the generator do? How do you use it?

Jonathan Fernandes
Jonathan Fernandes
Courses Plus Student 22,784 Points

Ok, no problem, I'll explain.

So, you know how ruby makes it super easy on your life for things like scaffolding? With one line of code, rails auto generates an entire scaffold of your model complete with all your CRUD actions.

That is simply the power of a generator. It takes something you would have had to build by yourself and makes it possible to repeat it all in one action.

So in my case, every project I make, I start by creating: 1) a git repository, 2) I add bootstrap to it, 3) I add my own personal framework, 4) I create the directory for organizing my stylesheets, 5) add some ruby helpers I use across all my projects, 6) setup up common partial files (like a header and a footer), 7) and add/commit it all to my repository.

what if instead of doing all those steps, I simply typed this in my command line:

$ rails generate auto_setup

Wouldn't that be way better than doing all those things by hand one by one when it's just the same commands and code for every project?

Now that example only saves me about 10 mins. But now think about a model and system that's a little bit more intense. For example, most of the websites I am building for people all require a user model, a sessions controller so that those users can log in, an admin type for those users so that certain actions can only be accessible by some users, as well as a blog model so they can create those blogs in the back end of their site. If I were to make that all from scratch, it can take me a couple hours to get everything done. But what if you could cut out 90% of the work? In other words, only thing you had to change was just a few minor things after everything gets auto generated. What took hours would now take me half an hour.

Right now, I am taking my generator and copy/pasting in every new project. That's annoying and I know it can be done because some of the documents online talk about it but nobody takes the time to explain it. In fact, I even found one video blog that showed how to create the generator and then mentioned that you can add that generator to a certain library so that it is available globally. Said he would show you how to add it globally in the next video... never made the next video on how to add it globally...

Let me know if you find it...

Would it be good enough for you to generate those things when you generate a new rails application? If so, Application Templates is what you want: http://guides.rubyonrails.org/generators.html

If you definitely want to be able to generate this stuff after the rails app has been generated, you'll have to create a generator and make it globally executable somehow.

Which do you want?

I'm genuinely interested in the latter, btw; I'll try to find time to work it out and I'll post back if I work out how to do it.

Jonathan Fernandes
Jonathan Fernandes
Courses Plus Student 22,784 Points

Yeah, I'm interested in the latter by executing it globally.

I know it can be done because I have seen people do it in their videos online and talk about it in blogs. The one resource I found where the guy did it, he did it with such an old version of ruby on rails that it didn't produce the same result on my setup. So yeah, I know it can be done, just a matter of figuring out how to do it.

1 Answer

Tim Knight
Tim Knight
28,888 Points

Jonathan,

I know I'm coming into this a little late but I think what you're looking for is a Rails Application Template. You can see this documented at http://edgeguides.rubyonrails.org/rails_application_templates.html but the idea is that you pass in a template script during the installation of your blog and it runs a bunch of your usual stuff to get you going.

You can use this to build files and create templates as well as install gems and setup git. Here are a few of the things I have in my template just to give you an idea on how it works.

app_setup.rb
gem "simple_form"
gem "haml"
gem "kaminari"
gem "email_validator"
gem "bootstrap-sass"

gem_group :development do
  gem "better_errors"
  gem "binding_of_caller"
  gem "annotate"
end

run "bundle install"

generate "simple_form:install --bootstrap"

generate "controller", "home index"
route "root to: 'home#index'"

initializer 'datetime_formats.rb', <<-CODE
Date::DATE_FORMATS.merge!({
  date:         '%B %e, %Y',            # April 20, 2012
  date_time:    '%m/%d/%Y %I:%M%p',     # 04/20/2012 12:00AM
  long_date:    '%A, %B %e, %Y',        # Friday, April 20, 2012
  super_short:  '%m/%d/%y'              # 04/20/12
})

Time::DATE_FORMATS.merge!({
  date_time:    '%m/%d/%Y %I:%M%p'      # 04/20/2012 09:27AM
})
CODE

# Setup local PostgreSQL databases
if yes?("Do you want me to setup the development databases?")
  run "createuser #{app_name}"
  run "createdb -O#{app_name} -Eutf8 #{app_name}_development"
  run "createdb -O#{app_name} -Eutf8 #{app_name}_test"
  rake "db:migrate"
end

# Create a gitignore file
append_file '.gitignore' do
  '.DS_Store'
end

# Setup git and add the project into Bitbucket
if yes?("Would you like me to setup git and push to bitbucket?")
  config['git_user'] = ask "What bitbucket username has the empty repository?"
  git :init
  git :add    => "."
  git :commit => "-m 'initial commit'"
  git :remote => "add origin ssh://git@bitbucket.org/#{config['git_user']}/#{app_name}.git"
  git :push   => "-u origin master"
end