Skip to content

Instantly share code, notes, and snippets.

@Kotauror
Created February 13, 2018 21:23
Show Gist options
  • Save Kotauror/17980174d272acae353206576b0d697d to your computer and use it in GitHub Desktop.
Save Kotauror/17980174d272acae353206576b0d697d to your computer and use it in GitHub Desktop.
Ruby + Postgresql - understanding the magic. This is my early attempt at understanding the magic which makes my ruby app work and connect to postgresql database.

Ruby + Postgresql - understanding the magic.

This is my early attempt at understanding the magic which makes my ruby app work and connect to postgresql database.

Program at the moment:

CONTROLLER :

app.rb

require 'sinatra/base'
require './lib/link'
require './database_connection_setup'

class BookmarkManager < Sinatra::Base
  get "/" do
    @links = Link.all
    erb(:index)
  end

  get '/getlink' do
    erb(:getlink)
  end

  post "/url" do
    Link.create(url: params[:url])
    redirect("/")
  end

  run! if app_file == $0
end

MODEL :

database_connection.rb

class DatabaseConnection
  def self.setup(database_name)
    @connection = PG.connect(dbname: database_name)
  end

  def self.query(sql)
   @connection.exec(sql)
  end
end

database_connection_setup.rb

require './lib/database_connection'

if ENV['ENVIRONMENT'] == 'test'
  DatabaseConnection.setup('bookmark_manager_test')
else
  DatabaseConnection.setup('bookmark_manager')
end

link.rb

require 'pg'
require_relative 'database_connection'

class Link
  def self.all
    result = DatabaseConnection.query("SELECT * FROM links")
    result.map { |link| link['url'] }
  end

  def self.create(hash)
    DatabaseConnection.query("INSERT INTO links (url) VALUES('#{hash[:url]}')")
  end
end

VIEWS :

index.erb:

<html>
  <head></head>
  <body>
    <form action="/getlink" method="get">
      <input type="submit" value="Add link">
    </form>
    <div>
      <ul>
        <% @links.each do |link| %>
          <li>
            <%= link %>
          </li>
        <% end %>
      </ul>
    </div>
  </body>
</html>

getlink.erb:

<form action="/url" method="post">
  <input type="text" name="url" placeholder="Enter URL here">
  <input type="submit" value="Add link">
</form>

OTHER RELEVANT (for this note) FILES

config.ru

require_relative "./app"
run BookmarkManager

spec_helper.rb

ENV['ENVIRONMENT'] = 'test'

require File.join(File.dirname(__FILE__), '..', 'app.rb')
require 'capybara'
require 'capybara/rspec'
require 'rspec'

Capybara.app = BookmarkManager

RSpec.configure do |config|

  config.before(:each) do
    require_relative './test_database_setup'
  end

  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end

  config.shared_context_metadata_behavior = :apply_to_host_groups

end

test_database_setup.rb

require 'pg'

connection = PG.connect(dbname: 'bookmark_manager_test')

connection.exec("TRUNCATE links;")
connection.exec("INSERT INTO links VALUES(1, 'http://www.makersacademy.com');")
connection.exec("INSERT INTO links VALUES(2, 'http://www.google.com');")
connection.exec("INSERT INTO links VALUES(3, 'http://www.facebook.com');")

How does it work - step by step:

--> when we run rspec

  • We run rspec
  • Because of running rspec, spec_helper.rb will be run as well.
  • spec_helper.rb sets the ENV[ENVIRONMENT] to "test".
    • then (next line of code in spec_helper), spec_helper.rb loads app.rb.
      • once the app.rb file is loaded, is will load all the files it requires, including database_connection_setup.rb
        • database_connection_setup.rb, knowing we're in the test environment, will connect us to the bookmark_manager_test database.
    • additionally, the spec_helper requires ./test_database_setup to be loaded before each test.
      • ./test_database_setup seeds our test database with links.

--> when we run rackup

  • First, config.ru file will be run and it will run our app.rb file.
  • once the app.rb file is loaded, is will load all the files it requires, including database_connection_setup.rb
  • database_connection_setup.rb will connect us to the bookmark_manager database, which is a database for a non-test environment.
    • we're not in the test environment because we didn't run spec_helper.rb and so we didn't set our environment to test.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment