model_from_schema:gen
This file contains 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
module ModelGenerator | |
MODELS = {} | |
module Evaluator | |
module_function | |
def create_table(table_name, *) | |
MODELS[table_name.classify] = { | |
has_many: [], | |
belongs_to: [], | |
has_many_foreign_key: [], | |
belongs_to_foreign_key: [] | |
} | |
end | |
# 無視 | |
def add_index(*) | |
end | |
def add_foreign_key(from, to, column: nil, name: nil) | |
fromc, toc = from.classify, to.classify | |
if column | |
MODELS[fromc][:belongs_to_foreign_key].push [to.singularize, column] | |
MODELS[toc][:has_many_foreign_key].push [from.singularize, column] | |
else | |
MODELS[fromc][:belongs_to].push to.singularize | |
MODELS[toc][:has_many].push from | |
end | |
end | |
end | |
def self.save | |
MODELS.each do |klass, data| | |
code = [ | |
"# #{klass}", | |
"class #{klass} < ApplicationRecord", | |
data[:has_many].map { |x| " has_many :#{x}" }, | |
data[:belongs_to].map { |x| " belongs_to :#{x}" }, | |
"end\n" | |
].flatten.join("\n") | |
path = Rails.root.join("app", "models", "#{klass.underscore}.rb") | |
unless File.exist?(path) | |
File.write(path, code) | |
puts "It generate the #{path}" | |
end | |
end | |
end | |
end | |
namespace :model_from_schema do | |
desc "Generate model files from db schema" | |
task gen: :environment do | |
s = ActiveRecord::Schema[7.0] | |
def s.define(*, &block) | |
ModelGenerator::Evaluator.class_eval(&block) | |
end | |
load Rails.root.join("db", "schema.rb") | |
ModelGenerator.save | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment