Question: How to connect rails development.sqlite3 database for the single ruby file?

Question

How to connect rails development.sqlite3 database for the single ruby file?

Answers 2
Added at 2017-07-01 18:07
Tags
Question

I have a main.rb for Telegram bot. For creating Admin panel of the bot I have used the Rails. So now I want to connect from main.rb file to the database which I created using Rails. How to do it?

Answers to

How to connect rails development.sqlite3 database for the single ruby file?

nr: #1 dodano: 2017-07-01 19:07

it seems you would like to use Plain Old Ruby Object (PORO) inside rails, here is some of my suggestion:

1. create app/services folder

create file for example main_service.rb

inside main_service.rb put your main.rb code inside

module MainService
  class Telegram
    def initialize
      ...
    end
    def send_telegram
      ...
    end
  end
end

2. inside your ruby controller for example admin_controller.rb

def show
  ...
  # create instance of your PORO class
  @message_svc = MainService::Telegram.new
  # call the method of your ruby class through rails controller
  @message_svc.send_telegram
  ...
end

3. restart your rails server

nr: #2 dodano: 2017-07-01 20:07

You need to do something like this inside of main.rb...

#!/usr/bin/ruby

require 'active_record'
require 'sqlite3'

ActiveRecord::Base.establish_connection(
  adapter:  'sqlite3',
  database: 'DB_NAME',
  username: 'DB_USER',
  password: 'DB_PASS',
  host:     'localhost'
)

# This will connect to the bots tables, probably not what you wanted.
class Bot < ActiveRecord::Base
end
Source Show
◀ Wstecz