How to get WordPress database table through Ruby script with dynamic active posting classes?

Currently, I have a website built in WordPress, and more than 1000 clients are registered. Will I be able to extract information from WordPress db into ruby ​​code

Is this method necessary for my clients? Without re-registering?

Note: This code should create dynamic record classes or models, and not manually define active record models.

+5
source share
1 answer

Without a Gem, you can achieve this with the Ruby script itself

I assumed that you have a rails application, you can create a rake task to retrieve data from a WordPress database

Step 1:

value = {host: "192.*.*.*", username: '', password: '', database: ''} ActiveRecord::Base.establish_connection( adapter: 'mysql2', encoding: 'utf8', pool: 5, host: value[:host], username: value[:username], password: value[:password], database: value[:database] ) 

Step 2:

Then you need to define the database tables

 database_tables = {:"database_name" => ["SaveContactForm7_1", "SaveContactForm7_2","SaveContactForm7_3","SaveContactForm7_4"]} 

Step 3:

 tables = database_tables[key] Key refers to the database name 

Step 4:

 tables.each do |table| MODEL_CLASS= table Object.const_set(MODEL_CLASS, Class.new(ActiveRecord::Base) { def self.name() MODEL_CLASS end;def self.table_name() MODEL_CLASS end }) records = MODEL_CLASS.constantize.all results = [] records.each do |record| set = {} columns = MODEL_CLASS.constantize.column_names p columns columns.each do |column| p record.send(column.to_sym) p set[:mobile] = record.send(column.to_sym) end results << set p record end p "Task done...." p results end 

As a result, you can see an array of hashes. you can insert into your active record models

Please feel free to give your suggestion for this.

+6
source

Source: https://habr.com/ru/post/1268700/


All Articles