Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override Rails scaffold generator

The scaffold generator in rails generates the MVC layers from the templates located in lib/rails/generators/erb/scaffold/templates railties path and from the lib/templates folder in your project.

If you copy the original files from the railties folder to your projects lib folder, then you'll be able to customize the original scaffold generator, as Daniel Fone explain in his blog.

The original Rails generator uses 5 files in the views layer:

  • _form.html.erb
  • edit.html.erb
  • index.html.erb
  • new.html.erb
  • show.html.erb

I was wondering if the there is a way to extend this behavior by adding another file to the set. like _header.html.erb or _info.html.erb (some partials that I've design).

like image 573
mariowise Avatar asked Sep 03 '15 20:09

mariowise


People also ask

How do you generate scaffold in rails?

To generate a scaffold for the post resource, enter the following command: rails generate scaffold Post name:string title:string content:text.

What is a Rails generator?

Rails generators are command line tools that are used for automating the process of creating or editing files with boiler plate code. In essence, they execute Ruby code much like a script and create or update files based on templates, user input and whatever logic necessary.

What does rails generate resource do?

Rails Generate Resource You enter the name of the resource you want to create along with the table column names and types. You can even assign foreign keys in this line of code so that you save time. Generating a resource does everything generating a model does, but it also creates a resource in the routes.


2 Answers

Well after a couple months I've found the solution. Instead of creating a new generator as the Rails documentation states, I override the default generator but in my projects lib folder.

enter image description here

The original scaffold_generator.rb is located at ~/.rvm/gems/ruby-2.1.0/gems/railties-4.2.4/lib/rails/generators/erb/scaffold. To add the new file (_info.html.erb) we will add it to the available_views method.

def available_views
    %w(index edit show new _form _info)
end

Hope it helps someone.

like image 156
mariowise Avatar answered Oct 10 '22 18:10

mariowise


For those who are lazy, here is a quick command to copy the default railties erb templates to the correct location in Rails:

mkdir -p lib/templates/erb/scaffold && \
cp $(bundle info railties --path)/lib/rails/generators/erb/scaffold/templates/* lib/templates/erb/scaffold
like image 38
Tim Krins Avatar answered Oct 10 '22 18:10

Tim Krins