ruby-on-railsruby-on-rails-5rails-generators

How to write a rails generator that would override the default scaffold javascript file?


Background:

Question:

Attempts:

All of my attempts above doesn't work: that is after both rails generate my_gem_name:install is ran, then running rails generate scaffold some_model_name still produces the original default javascript file, and not the expected console.log('JUST TESTING!!!!!!!') content (as I described above)


Solution

  • I finally solved it by the following. Hopefully, it would be helpful to anyone:

    For Step 1 (Overriding the javascript file):

    For Step 2 (Dynamic javascript file content):

    Complete Solution Looks Like:

    lib/generators/my_gem_name/install_generator.rb

    module MyGemName
      class InstallGenerator < Rails::Generators::Base
        source_root File.expand_path('../templates', __FILE__)
    
        class_option :javascript_engine, desc: 'JS engine to be used: [js, coffee].'
    
        def copy_js_scaffold_template
          copy_file "javascript.#{javascript_engine}.rb", "lib/templates/#{javascript_engine}/assets/javascript.#{javascript_engine}"
        end
    
        private
    
        def javascript_engine
          options[:javascript_engine]
        end
      end
    end
    

    lib/generators/my_gem_name/templates/javascript.coffee.rb

    # Place all the behaviors and hooks related to the matching controller here.
    # All this logic will automatically be available in application.js.
    # You can use CoffeeScript in this file: http://coffeescript.org/
    SomeJavascriptCode.doSomething({model: '<%= singular_table_name.camelcase %>'})
    

    Then, on terminal:

    rails generate my_gem_name:install
      Running via Spring preloader in process 42586
            create lib/templates/coffee/assets/javascript.coffee
    
    rails generate scaffold user email first_name last_name
      Running via Spring preloader in process 43054
            invoke active_record
            create   db/migrate/20170721152013_create_users.rb
            create   app/models/user.rb
            ...
            invoke assets
            invoke   coffee
            create     app/assets/javascripts/users.coffee
            ...
    
    cat app/assets/javascripts/users.coffee
      # Place all the behaviors and hooks related to the matching controller here.
      # All this logic will automatically be available in application.js.
      # You can use CoffeeScript in this file: http://coffeescript.org/
      SomeJavascriptCode.doSomething({model: 'User'})