How to bind tiny_tds connection in ruby ​​/ sinatra via database.yml (or other)?

I am trying to figure out how to retrieve data from a database without having to place a connection string at the top of each ruby ​​file.

I learn the basics of ruby ​​through the small Sinatra application that I compile, which retrieves data from an MSSQL database.

So far, I have managed to create various simple erb pages that display data from the MSSQL database using the following code structure at the top of each file: -

<% client = TinyTds::Client.new(:username => 'name', :password => 'password', :dataserver => 'hostname', :database => 'database') %> <% data = client.execute("SELECT * from tablename") %> 

From the books, tutorials and online tutorials that I found based on many configurations for PostgreSQL or MySQL databases, it seems to me that I need to create a central file to store the connection data (for example, database. Yml), and then referring to that somewhere / somehow in my application.

Will this be correct, and should I do this in my main.rb file so that each of my .erb files does not require a connection string or do I still need to reference the database in each .erb file

I noticed links to creating database configuration variables, such as: -

 db_config = YAML.load(File.Open("/path_to_file/database.yml")) [ENV['RAILS_ENV']] 

but this is clearly similar to Rails applications.

Can I do something similar for my Sinatra app?

Thanks.

+4
source share
1 answer

This should work:

 require "sinatra" require "sinatra/config_file" config_file 'path/to/config.yml' DB = TinyTds::Client.new( :username => settings.name, :password => settings.password, :dataserver => settings.hostname, :database => settings.database ) get '/' do @result = DB.do_stuff haml :index end 

What I would like to suggest is that you are looking for an ORM that supports TinyTDS, and use this to set up a database connection and run queries. I use Sequel and I know that it supports TinyTDS , but I am sure that others do too.

I also suggest not putting things like database settings in a file that is checked against the original control as confidential information. I prefer to bring these things into production environment variables and use the configuration file to load environment variables in development (for convenience). Using the above example:

 DB = TinyTds::Client.new( :username => ENV["name"], :password => ENV["password"], :dataserver => ENV["hostname"], :database => ENV["database"] ) 

These env variables are loaded into the memory of the production server, which makes them a bit more secure. For development, I upload YAML files before starting Sinatra, adding each value to ENV var. I do not suggest that this be a standard way, but how do I do it.

+1
source

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


All Articles