Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fetch WordPress Data Base Table via Ruby script with dynamic active record classes?

Tags:

I currently have a website that is built in WordPress, and have over 1000 customers registered. Would I be able to extract the information from the WordPress db in ruby code

Need way that's seamless for my customers? Without requiring registering again?

Note: This code should create active record classes or models dynamically instead of manually defining active record models

like image 463
vel murugan Avatar asked Jun 09 '17 10:06

vel murugan


1 Answers

With out having the Gem You can achieve this via Ruby script itself

I assumed you have rails application from there you can create rake task to fetch the data from 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 Define the database tables needs to be fetched

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 the array of hashes. you can insert into your active record models

Please Feel free to give your suggestion for this

like image 108
vel pradeep.MS Avatar answered Sep 29 '22 23:09

vel pradeep.MS