Skip to content

Instantly share code, notes, and snippets.

@jonahgeorge
Last active June 14, 2016 18:08
Show Gist options
  • Save jonahgeorge/1ec3ae9f38488f65fd90 to your computer and use it in GitHub Desktop.
Save jonahgeorge/1ec3ae9f38488f65fd90 to your computer and use it in GitHub Desktop.
Generates PHP ActiveRecord class files for the #MECOP system
require 'active_support/all'
require 'mysql2'
require 'erb'
def get_primary_key(client, table)
query = "SHOW INDEX FROM #{table} WHERE Key_name = 'PRIMARY';"
result = client.query(query).first
result["Column_name"]
end
def format_column(column, primary_key)
if primary_key == column
return "id"
end
column = column.underscore
column = column[3..-1] + "_id" if column[0,3] == "id_"
return column
end
def format_class_name(table)
table = table[2..-1] if table[0,2] == "L_"
table = table[2..-1] if table[0,2] == "D_"
table = table[3..-1] if table[0,3] == "tbl"
table = table.gsub("Std_", "Student")
table = table.gsub("STD_", "Student")
table = table.gsub("EMP_", "Employee")
table = table.gsub("Emp_", "Employee")
table = table.gsub("ORG_", "Organization")
table = table.gsub("Org_", "Organization")
table = table.gsub("APP_", "Application")
table = table.gsub("App_", "Application")
table.classify
end
def get_columns(client, table)
query = "SHOW COLUMNS FROM #{table};"
columns = client.query(query)
columns.map { |c| c["Field"] }
end
client = Mysql2::Client.new(
:host => "localhost",
:username => "root",
:password => "",
:port => 3306,
:database => "mecop-www_development"
)
ignored_tables = [
"S_ACCOUNT_GROUP", "S_ACCOUNT", "S_GROUP_GRANTED", "S_GROUP",
"S_OBJECT_DATA_ITEM", "S_PRIVILEGE", "S_REPORT_MENU", "S_REPORT",
"Save_D_ORGANIZATION", "Save_tblMember", "Save_tblStudentPassword",
"schema_migrations", "blazer_audits", "blazer_checks",
"blazer_dashboard_queries", "blazer_dashboards", "blazer_queries"
]
tables = client.query('SHOW TABLES')
.map { |t| t["Tables_in_mecop-www_development"] }
.reject { |t| ignored_tables.include?(t) }
Dir.mkdir('models')
tables.each do |table|
@table = table
@class_name = format_class_name(table)
@primary_key = get_primary_key(client, table)
@columns = get_columns(client, table)
template = <<~PHP
<?php
namespace App\\Eloquent;
use App\\Models\\ResumeWritingExam;
use Illuminate\\Database\\Eloquent\\Model;
use Sofa\\Eloquence\\Eloquence;
use Sofa\\Eloquence\\Mappable;
class <%= @class_name %> extends Model
{
use Eloquence;
use Mappable;
protected $table = "<%= @table %>";
protected $primaryKey = "<%= @primary_key %>";
protected $maps = [
<% @columns.each do |column| %> "<%= format_column(column, @primary_key) %>" => "<%= column %>",
<% end %>];
public $timestamps = false;
}
PHP
code = ERB.new(template).result
file = File.new("models/#{@class_name}.php", 'a')
file.write(code)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment