Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Hook into rails model generators to update a scope that requires changes each time a new model is added
# 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
You can’t perform that action at this time.