Skip to content

Instantly share code, notes, and snippets.

@vishaltelangre
Created November 7, 2013 15:01
Show Gist options
  • Save vishaltelangre/7356033 to your computer and use it in GitHub Desktop.
Save vishaltelangre/7356033 to your computer and use it in GitHub Desktop.
connection w/ a non-standard mysql db using active-record and retrieving tables
#! /usr/bin/env ruby
#
# Establishes connection with a MySQL db and access its tables
# which have non-standard names, such as user, accounts.
#
require 'active_support/inflector'
require 'active_record'
require 'mysql2'
ActiveRecord::Base.establish_connection({
adapter: 'mysql2',
host: 'localhost',
username: 'root',
password: 'mysecret',
database: 'blah_db'
})
models = []
ActiveRecord::Base.connection.tables.each do |t|
model = Class.new(ActiveRecord::Base) do
self.table_name = t
end
Object.const_set(t.singularize.camelize, model)
models << model
end
puts models.map(&:name).join(", ") + "\n"
models.map{|m| puts m.inspect }.join("\n")
# OUTPUT
# Account, User
# Account(id: integer, user_id: integer, cc_number: string)
# User(id: integer, name: string, email: string, mobileno: string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment