How to test Ruby OCI8 database services - ruby

Are there any tutorials or examples of testing Ruby OCI8 database services?

See "C:\RubyXXX\lib\ruby\gems\1.9.1\gems\ruby-oci8-2.1.0-x86-mingw32\test\test_oci8.rb" or wherever it is on your drive.
Lots of weblinks i'm not going to include, you can google them yourselve.
A very simple example
require 'oci8'
oci = OCI8.new('schema','password','db.server')
oci.exec('select * from table') do |record|
puts record.join(',')
end
Some unit testing for active-record and sqlite, you can adapt this for oci8
require 'active_record'
require "test/unit"
ActiveRecord::Base.establish_connection(
:adapter => "sqlite3",
:database => "sample.db"
)
class Album < ActiveRecord::Base;end
class Tester < Test::Unit::TestCase
def test_title
assert_equal('Sticky Fingers', Album.find_by_title('Sticky Fingers').title)
end
end

Related

Can't connect to local MySQL server through socket. I want to connect to REMOTE db

This is my code.
I want to connect to remote database
require 'bundler/setup'
#require "mysql"
#require 'mysql2'
#require "active_record"
Bundler.require
#db_host = ENV["HOST"]
#db_user = ENV["USER"]
#db_pass = ENV['PASSWORD']
#db_name = "db_name"
require "active_record"
ActiveRecord::Base.establish_connection(
:adapter => 'mysql2',
:database => #db_name,
:username => #db_user,
:password => #db_pass,
:host => #db_host)
class ConversionRate < ActiveRecord::Base
end
class ConversionRateMonthly < ActiveRecord::Base
self.table_name = "conversion_rates_monthly"
end
class KdpReport < ActiveRecord::Base
end
class SalesCalculator
def run
p KdpReport.count
end
end
calculator = SalesCalculator.new
calculator.run
But I get this error:
/home/jonsdirewolf/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/mysql2-0.4.9/lib/mysql2/client.rb:89:in `connect': Can't connect to local MySQL server through socket
'/var/run/mysqld/mysqld.sock' (2) (Mysql2::Error)
It is strange but yesterday my code worked. what may be wrong? I want to connect to remote db, not local. And btw I use ruby without rails.
So, the problem is in empty environment var ENV["HOST"].
When host, passed to ActiveRecord is nil or equl to string localhost - AR will try to connect to db using socket.

how do I read from a Database in ruby sinatra using active record

I want to read entrys from a Database using active_record and keep getting diffrent Errors like: Name error and can't find the database or it can't execute the query.
so my question here is how do i read from a database or execute SQL-queries and for example write the result into a variable?
require 'rubygems'
require 'sinatra'
require 'active_record'
require 'sqlite3'
ActiveRecord::Base.establish_connection(
:adapter => "sqlite3",
:database => "test.db"
)
class Article < ActiveRecord::Base
end
#ActiveRecord::Migration.create_table :users do |t|
# t.string :name
#end
class App < Sinatra::Application
end
get '/' do
output = users.select(:all)
f = File.open('name','a'); f.write(output); f.close
#puts User.first
To read the data from the users table, you'd simply do:
class User < ActiveRecord::Base
end
get '/' do
#users = User.all
puts "Grabbed #{#users.size} user(s) from database"
end

Unable to make a rake-tasks file and make it work properly

I decided to create a rake tasks for my Sinatra project and not to use the ready ones.
#Rakefile
require 'rake/testtask'
require 'rake/clean'
Dir.glob("tasks/*.rake").each { |r| import r }
#/tasks/seed.rake
require 'rubygems'
require 'bundler'
Bundler.require
require 'mongoid'
require_relative '../models/user'
namespace :db do
task :seed do
puts 'Creating a user....'
user1 = User.new email: "email1#gmail.com", password: "test123"
user1.save!
puts 'User has been created.'
end
end
#user.rb
require 'bcrypt'
require 'digest/md5'
require 'openssl'
class User
include Mongoid::Document
include Mongoid::Timestamps
#.........
#gemfile (partly)
source 'http://rubygems.org'
gem 'bcrypt-ruby', require: 'bcrypt'
And I've got the error of "Creating a user....
rake aborted!
undefined method `create!' for BCrypt::Password:Class
/home/alex/ruby_projects/service/models/user.rb:47:in `password='"
where #47 looks like
def password= pass
self.hashed_password = BCrypt::Password.create! pass, cost: 10
end
Note that in normal development everything works just fine. So I missed to require a file I think.
Your thoughts?
p.s. Even if I put
require 'bcrypt'
require 'digest/md5'
require 'openssl
to /tasks/seed.rake the error remains.
It appears you are using a non-existant method from BCrypt::Password. According to the docs, there is only a .create method and no .create! method. Switch to BCrypt::Password.create and it should work.
def password= pass
self.hashed_password = BCrypt::Password.create pass, cost: 10
end

ActiveRecord and sqlite3 : find does not accept any condition?

I have a problem I can't figure out here. I'm writing a ruby script that deals with an sqllite database.
require 'rubygems'
require 'sqlite3'
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => "sqlite3",
:database => "../database/my.db"
)
class KeyWord < ActiveRecord::Base
set_table_name "keywords"
end
# THIS STATEMENT WORKS (finds the first record, returns "ruby") :
KeyWord.find(1).keyval
# THOSE STATEMENTS RETURN NO RESULT :
KeyWord.find(:all, :conditions => {:keyval => "ruby"})
KeyWord.find_by_sql("SELECT * FROM keywords WHERE keyval='ruby'")
KeyWord.find_by_keyval("ruby")
This is how the table was created :
create_table :keywords do |table|
table.column :keyval, :text
end
Does anyone know where this could come from ?
Thanks,
R.
I see a couple of issues here.
I'm not sure why you're manually setting your table name.
ActiveRecord assumes that your model name is camelCased. So... AR
would, by default, search for a table called key_words. Why not just
go with that?
Pay attention to which version of active record you are
using. Passing in conditions is deprecated. You should be using the
.where syntax. So... you would need to do KeyWord.where(:keyval
=> 'ruby').first or end in .all for a collection of results.
If you are just fooling around, you can use sqlite3 in memory.
ActiveRecord::Base.establish_connection( adapter: 'sqlite3',
database: ":memory:")
Also don't forget to define your schema!
Here is full code w/ more modern syntax.
require 'rubygems'
require 'sqlite3'
require 'active_record'
ActiveRecord::Base.establish_connection( adapter: 'sqlite3', database: ":memory:" )
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define(version: 2) do
create_table :key_words do |t|
t.text :keyval
end
end
class KeyWord < ActiveRecord::Base
end
Keyword.create!(:keyval => 'ruby')
# THESE STATEMENTS WORK:
KeyWord.find(1).keyval
KeyWord.where(:keyval => 'ruby').first
KeyWord.where(:keyval => 'ruby').all
KeyWord.find_by_sql("SELECT * FROM key_words WHERE keyval='ruby'")
KeyWord.find_by_keyval("ruby")

Sinatra/CouchDB error?

I'm working on my first Sinatra/CouchDB project and I'm getting an error I can't explain.
Here's my rackup (config.ru) file:
require 'rubygems'
require 'couchrest'
require 'patina'
set :environment, :development
set :root, File.dirname(__FILE__)
set :run, false
FileUtils.mkdir_p 'log' unless File.exists?('log')
log = File.new("log/sinatra.log", "a")
$stdout.reopen(log)
$stderr.reopen(log)
set :db, CouchRest.database!("http://127.0.0.1:5984/test")
run Sinatra::Application
And here's the app file (patina.rb):
require 'rubygems'
require 'sinatra'
require 'couchrest'
require 'haml'
class Article < CouchRest::ExtendedDocument
use_database settings.db
property :title
timestamps!
view_by :title
end
get '/' do
#db = settings.db
haml :index
end
Without the class definition in patina.rb, the route returns a page that displays the #db property as I was expecting. However, when I add the class definition to patina.rb I get "Ruby (Rack) application could not be started" error message.
Obviously this has something to do with my class definition, but I can't figure out what the problem is and the error message doesn't seem that helpful to me.
Also, I'd actually prefer to have the class definition in a separate file (Article.rb), but I can't figure out how to do that in the context of my Sinatra app.
Any help would be greatly appreciated!
EDIT:
See my answer below.
After a lot of googling, I discovered that the 1.4 series of json.gem are known to cause a lot of problems. I uninstalled all the json gems I had and installed json-1.2.4.gem instead. I have everything working correctly now. Here's the setup I'm using:
config.ru (Rackup file):
require 'application'
set :environment, :production
set :root, File.dirname(__FILE__)
set :run, false
FileUtils.mkmdir_p 'log' unless File.exists?('log')
log = File.new('log/sinatra.log', 'a+')
$stdout.reopen(log)
$stderr.reopen(log)
run Sinatra::Application
environment.rb:
require 'rubygems'
require 'couchrest'
require 'haml'
require 'ostruct'
require 'sinatra' unless defined?(Sinatra)
configure do
SiteConfig = OpenStruct.new(
:title => 'Application Title',
:author => 'Your Name',
:url_base => 'Your URL',
:url_base_db => 'Your CouchDB Server',
:db_name => "Your DB Name"
)
# load models
$LOAD_PATH.unshift("#{File.dirname(__FILE__)}/lib")
Dir.glob("#{File.dirname(__FILE__)}/lib/*.rb") { |lib| require File.basename(lib, '.*') }
end
lib/contact.rb (Model example, models auto-loaded in environment.rb):
class Contact < CouchRest::ExtendedDocument
include CouchRest::Validation
use_database CouchRest.database!((SiteConfig.url_base_db || '') + SiteConfig.db_name)
property :name
timestamps!
view_by :name
end
application.rb:
require 'rubygems'
require 'sinatra'
require 'environment'
configure do
set :views, "./views"
end
error do
e = request.env['sinatra.error']
Kernel.puts e.backtrace.join("\n")
'Application error'
end
helpers do
end
get '/new/?' do
haml :new
end
post '/save/?' do
#contact_name = params[:contact_name]
#contact = Contact.new
#contact.name = #contact_name
#contact.save
haml :save
end
get '/' do
haml :index
end
Hope this helps someone in the future!
try requiring 'patina' after setting :db. I think the class body of Article is executing the use_database method before the setting exists.
you should be able to put Article in article.rb (ruby naming convention is UpperCamel for classes, but under_scores for the files in which classes are defined) and then require 'article' in patina.rb.
thats the only thing that stood out for me, so let me know if that works.

Resources