Created
March 20, 2019 22:26
-
-
Save darrenterhune/42c7e1cc1cb87adb21c1e09eb807a5a8 to your computer and use it in GitHub Desktop.
Hook into rails model generators to update a scope that requires changes each time a new model is added
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/environments/development.rb | |
config.generators do |generator| | |
generator.orm :hooks | |
end | |
# lib/generators/rails/hooks/hooks_generator.rb | |
require 'rails/generators/active_record/model/model_generator' | |
module Rails | |
module Generators | |
hide_namespace 'hooks' | |
class HooksGenerator < ActiveRecord::Generators::ModelGenerator | |
source_root "#{base_root}/active_record/model/templates" | |
def create_fund_scoping_annotation | |
model = Rails.root.join("app", "models", "fund.rb") | |
line = 'scope :having_investments_in' | |
gsub_file model, /(#{Regexp.escape(line)})/mi do |match| | |
"#{match}_blown_up" | |
end | |
puts 'Please update fund scope :having_investments_in' \ | |
'Add relative scopes if needed and update :having_investments_in' | |
end | |
private | |
def gsub_file(path, regexp, *args, &block) | |
content = File.read(path).gsub(regexp, *args, &block) | |
File.open(path, 'wb') { |file| file.write(content) } | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment