简体   繁体   中英

How to generate controller/models/views inside lib folder? (Ruby on Rails)

I'm kind of new to ruby and I encountered this problem.

rails generate model whatever creates some files inside the /app/models/ folder. But what if I want to generate those inside lib for example in /lib/modules/monitor/app/

I've been searching and didn't find anything. I tried putting the path in the command but it doesn't work, it just creates the specified path inside the /app folder.

Right now what I'm doing is creating a controller for example, and copying the created files from /app to /lib/modules/monitor/app, which is not that good since you have to copy manually all the files.

Is there a better way to do this?

There doesn't seem to be any conventional rails reason for copying files from the app to lib. Will the rails app even be able to use them? My guess is probably not without breaking a lot of stuff. But if you simply want to use rails generators to generate files and have them automatically copy to some other location, you might want to check out this gem

gem install listen

You would need to write a ruby script and run it from the root of your project before using your rails generators for example in a file bin/file_duper.rb

#!/usr/bin/env ruby
require 'listen'
rails_root = Dir.exists?(Dir.pwd + '/app') ? Dir.pwd : nil
abort('This script must be run from rails root') unless rails_root
dest_folder = Dir.pwd + '/lib/modules/'
unless Dir.exists?(dest_folder)
  FileUtils.mkdir(dest_folder)
end

listener = Listen.to(rails_root, dest_folder) do |modified, added, removed|
  added.each do |file|
    FileUtils.cp(file, dest_folder + file.split('app/')[1])
  end
  modified.each do |file|
    FileUtils.cp(file, dest_folder + file.split('app/')[1])
  end
  removed.each do |file|
    FileUtils.rm(file, dest_folder + file.split('app/')[1])
  end
end

listener.start 
sleep

Now make sure you're in the rails project root before running this script. You might want to run this detached (in the background).

ruby bin/file_duper.rb # running in terminal can be killed with ctrl + c

If you want this to run in the background you can run it like

ruby bin/file_duper.rb &

This will run several processes in the background under the hood using ruby rb-fsevent. If you need to stop these processes you can do

pgrep -f rb-fseven | xargs kill

Words of caution: This script is not heavily tested and may have defects. Also this type of file duplication would likely cause problems with git version control so you may need to add lib/modules/ to your projects .gitignore file assuming you're using version control.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM