Gem not found when I have just installed it - ruby

I am creating a Ruby script which reads data from an Excel sheet and put its data on a MySQL database. I have written it and installed the necessary gems. However, when I try to run it via my cPanel host and I get the following error:
Array ( [0] => /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require': no such file to load -- ruby-mysql (LoadError) [1] => from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' [2] => from ../ruby/InsertarFaltantesExcel.rb:2 )
Ruby Code:
require 'rubygems'
require 'ruby-mysql'
require 'spreadsheet'
#load './spreadsheet.rb'
con = Mysql.connect('xx', 'xx', 'xx','xx')
ARGV = "--help" if ARGV.empty?
workbook = Spreadsheet.open(ARGV[0])
sheet = workbook.worksheet(0)
sheet.each do |row|
#faltantes = {
"id_verificador" => "#{row[0]}",
"order_id" => "#{row[1]}",
"id_proveedor" => "#{row[28]}",
"shipping" => "#{row[10]}",
"ean" => "#{row[4]}",
"isbn" => "#{row[5]}",
"description" => "#{row[8]}",
"sku" => "#{row[9]}",
"cost" => "#{row[40]}",
"order_price" => "#{row[14]}",
"master" => "#{row[39]}",
"quantity_purchased" => "#{row[11]}",
"total_price" => "#{row[12]}",
"condition" => "#{row[33]}",
"tracking" => "#{row[29]}"
}
insertar_faltantes(#faltantes, con)
end
def insertar_faltantes(hash, con)
statement - con.prepare("INSERT INTO articulos(art_id_verificador, art_id_orden, art_id_proveedor, art_shipping, art_N13, art_ISBN, art_titulo, art_SKU, art_cost, art_precio, art_master, art_cantidad, art_total, art_condition,
art_tracking) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?);")
statement.execute "#{hash['id_verificador']}", "#{hash['order_id']}", "#{hash['id_proveedor']}", "#{hash['shipping']}", "#{hash['ean']}", "#{hash['isbn']}", "#{hash['sku']}", "#{hash['cost']}", "#{hash['order_price']}","#{hash['master']}",
"#{hash['quantity_purchased']}", "#{hash['condition']}", "#{hash['tracking']}"
end

The gems in ~/ruby/gems/gems/ are not being recognised by your Ruby executable. Find where all the other gems are being kept and move these ones into there.
Alternatively, try using a different package manager. If you have installed gems successfully in the past, use the manager you used for that.

Related

Retrieve MongoDB GridFS file using Ruby

I am trying to retrieve a binary file that I successfully stored using GridFS.
I am using MongoDB v3.0.6, Ruby 2.0.0 and MongoDB Ruby Driver v 2.0.1 on Mac OS X.
Is there a working example?
Looking over the docs, it seems like this should work:
client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
client.database.fs.find_one(:filename => 'new-file.txt') #=> Returns a Mongo::Grid::File
Here's how to stream it to a file:
client.database.fs.open_download_stream(file_id) do |stream|
IO.write('some-file', stream.read)
end
The following code works:
require 'rubygems'
require 'mongo'
include Mongo
$client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'garden')
Mongo::Logger.logger.level = ::Logger::ERROR
$files = $client[:files]
puts 'connected!'
# Upload file
fs = $client.database.fs
$file = File.open("delete.rb")
$file_id = fs.upload_from_stream("delete.rb", $file)
$file.close
$file_to_write = File.open('perfectCopy', 'w')
fs.download_to_stream($file_id, $file_to_write)
Mihalis.

Ruby Google API Resource Not Found: Domain

I've managed to fix the original issue below by removing the .readonly from the URL.
I'm now being presented with this error:
{"error"=>{"errors"=>[{"domain"=>"global", "reason"=>"notFound", "message"=>"Resource Not Found: domain"}], "code"=>404, "message"=>"Resource Not Found: domain"}}
Again, I've taken a look at this error online but all the links seem to go to an error page on Google and nothing to help determine a fix for this error.
Original Issue
I'm trying to use the below script to access to Google Directory API using Ruby but I'm receiving an error when I try to execute the script.
Script
#!/usr/bin/env ruby
require 'rubygems'
require 'json'
require 'google/api_client'
require 'active_support/core_ext/hash'
# The value of client_email from the JSON file goes here
SERVICE_ACCOUNT_EMAIL = 'xxxxxxxxx-bk7gbhr8k2dfvtidm0cc0msnipo34c8p#developer.gserviceaccount.com'
# This should be an Admin
ACT_ON_BEHALF_EMAIL = 'xxxxxx#gmail.com'
# File path to the certificate
SERVICE_ACCOUNT_PKCS12_FILE_PATH = '/home/xxxx/3ce8a60d43a8fa5cb747441fdfd90c3b91d6f45b-privatekey.p12'
key = Google::APIClient::PKCS12.load_key(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'notasecret')
asserter = Google::APIClient::JWTAsserter.new(SERVICE_ACCOUNT_EMAIL, 'https://www.googleapis.com/auth/admin.directory.user.readonly', key)
client = Google::APIClient.new(:application_name => 'GAAccountAudit')
client.authorization = asserter.authorize(ACT_ON_BEHALF_EMAIL)
api = client.discovered_api('admin', 'directory_v1')
result = client.execute(
:api_method => api.users.list,
:parameters => {
'domain' => 'http://www.xxxxxx.com',
'orderBy' => 'givenName',
'maxResults' => 500,
'fields' => 'users(id,etag,primaryEmail,name,suspended)',
}
)
users = JSON.parse(result.body, {:symbolize_names => true})[:users]
users.each do |u|
puts "#{u[:name][:fullName]} <#{u[:primaryEmail]}>"
end
Error
{"error" : "unauthorized_client","error_description" : "Unauthorized client or scope in request."}
I've read up on this error but I've not been able to find a conclusive answer to this. Could anyone please advise how I resolve this error?

Why Am I getting a NoMethodError when using the google API to run a query against google Big Query?

I'm trying to run a Query against Google Big Query, using the Ruby API.
This is my first project with Ruby and I'm still learning the language.
This is also my first project using the Google API.
ENVIORNMENT:
Windows 7
Ruby 1.9
Faraday 0.90
Goolge API - Service Account Authentication
My Code runs without giving any warnings or error messages through:
#client.authorization.fetch_access_token!
doc = File.read('bigQueryAPI.json')
#bigQuery = #client.register_discovery_document('bigquery', 'v2', doc)
NOTE: #bigQuery is loaded from a file because when I try to load #bigquery with
#bigquery = #client.discovered_api('bigquery', 'v2')
I get Google::APIClient::ClientError: Not Found and inspect only prints
#<Google::APIClient::API:0x17c94cc ID:bigquery:v2>
However If I save the Big Query API as a text file from
https://www.googleapis.com/discovery/v1/apis/bigquery/v2/rest
and then load it as a text file with
doc = File.read('bigQueryAPI.json')
#bigQuery = #client.register_discovery_document('bigquery', 'v2', doc)
then #bigQuery.inspect actually returns something useful.
#bigQuery.inspect output.
However, When I try to actually run a query, like so:
result = #client.execute!(
:api_method => #bigQuery.batch_path.query,
:body_object => { "query" => "SELECT count(DISTINCT repository_name) as repository_total, " +
"count(payload_commit) as commits_total, " +
"count(DISTINCT repository_name) / count(payload_commit) as average, " +
"FROM [githubarchive:github.timeline]" }, #,
:parameters => { "projectId" => #project_id })
I get the following error:
NoMethodError: undefined method `query_values' for nil:NilClass
Here's the Full Stacktrace of the error:
1) Error:
test_averages(Test_GitHub_Archive):
NoMethodError: undefined method `query_values' for nil:NilClass
C:/Ruby193/lib/ruby/gems/1.9.1/gems/google-api-client-0.7.1/lib/google/api_client/request.rb:145:in `uri='
C:/Ruby193/lib/ruby/gems/1.9.1/gems/google-api-client-0.7.1/lib/google/api_client/request.rb:101:in `initialize'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/google-api-client-0.7.1/lib/google/api_client.rb:518:in `new'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/google-api-client-0.7.1/lib/google/api_client.rb:518:in `generate_request'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/google-api-client-0.7.1/lib/google/api_client.rb:583:in `execute!'
C:/Users/tfburton/Documents/private/ProjectSuggestor/RubyStats/GitHub_Archive.rb:39:in `get_averages'
C:/Users/tfburton/Documents/private/ProjectSuggestor/RubyStats/TestSpec/test_GitHub_Archive.rb:26:in `test_averages'
Here is the results for #client.inspect
NOTE: I would have pasted here, but my post ended over the length limit.
After doing some digging. It looks like I'm not passing the proper #bigQuery prameter to get the query function.
Looking at the dump for #bigQuery.inspect I need to pass the method at line 751.
However I can't seem to figure out how to pass that method.
If you strip out the rest of the inspect output the "path" looks like this:
{ "resources => { "jobs" => { "methods" => { "query"
I've tried #bigQuery.Jobs.query and that results in an error stating that #bigQuery.Jobs doesn't exist.
So am I creating #bigQuery correctly?
Why doesn't #bigQuery.Jobs.query work?
Here's how I got it to work with the bigquery.jobs.query method, which is probably what you need.
I had to set OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE because otherwise the authorization process would fail miserably, but that might be specific to min Win7/MgitSys environment. In any case, this specific line is not safe in prod.
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'
require 'google/api_client/auth/file_storage'
require 'openssl'
require 'json'
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
# Initialize the client.
client = Google::APIClient.new(
:application_name => 'Example Ruby application',
:application_version => '1.0.0'
)
CREDENTIAL_STORE_FILE = "#{$0}-oauth2.json"
file_storage = Google::APIClient::FileStorage.new(CREDENTIAL_STORE_FILE)
# Initialize Google+ API. Note this will make a request to the
# discovery service every time, so be sure to use serialization
# in your production code. Check the samples for more details.
#bigQuery = client.discovered_api('bigquery', 'v2')
# Load client secrets from your client_secrets.json.
client_secrets = Google::APIClient::ClientSecrets.load
file_storage = Google::APIClient::FileStorage.new(CREDENTIAL_STORE_FILE)
if file_storage.authorization.nil?
client_secrets = Google::APIClient::ClientSecrets.load
# The InstalledAppFlow is a helper class to handle the OAuth 2.0 installed
# application flow, which ties in with FileStorage to store credentials
# between runs.
flow = Google::APIClient::InstalledAppFlow.new(
:client_id => client_secrets.client_id,
:client_secret => client_secrets.client_secret,
:scope => ['https://www.googleapis.com/auth/cloud-platform','https://www.googleapis.com/auth/bigquery']
)
client.authorization = flow.authorize(file_storage)
else
client.authorization = file_storage.authorization
end
puts "authorized, requesting"
# Make an API call.
result = client.execute!(
:api_method => #bigQuery.jobs.query,
:body_object => { "query" => "SELECT count(DISTINCT repository_name) as repository_total, " +
"count(payload_commit) as commits_total, " +
"count(DISTINCT repository_name) / count(payload_commit) as average, " +
"FROM [githubarchive:github.timeline]" }, #,
:parameters => { "projectId" => "845227657643" })
puts JSON.dump result.data

Obtaining a list of Cloudfiles with fog - stack level too deep

I'm attempting to obtain a list of all files in my Rackspace Cloudfiles account using the "fog" gem (github.com/fog/fog). However, I keep running into a stack level too deep error.
require 'rubygems'
require 'fog'
RACKSPACE_USERNAME = 'USERNAME'
RACKSPACE_API_KEY = 'API_KEY'
connection_rackspace = Fog::Storage.new({
:provider => 'Rackspace',
:rackspace_username => RACKSPACE_USERNAME,
:rackspace_api_key => RACKSPACE_API_KEY
})
connection_rackspace.directories.each do |directory_rackspace|
directory_rackspace.files.each do |file_rackspace|
puts file_rackspace.key
end
end
I gather that it has to do with that "each" loop, but can't figure out where to go from here.

Parsing CSV with headers in Ruby?

This works:
require 'csv'
file = CSV.open(filename)
puts file.shift
This does not:
require 'csv'
file = CSV.open(filename, :headers=>true)
puts file.shift
I get:
C:/Program Files (x86)/IronRuby 1.1/Lib/ruby/1.9.1/csv.rb:2177:in `convert_field
s': undefined method `with_index' for IronRuby.Builtins.Enumerator:Enumerator (N
oMethodError)
from C:/Program Files (x86)/IronRuby 1.1/Lib/ruby/1.9.1/csv.rb:2218:in `
parse_headers'
from C:/Program Files (x86)/IronRuby 1.1/Lib/ruby/1.9.1/csv.rb:1918:in `
shift'
from C:/Program Files (x86)/IronRuby 1.1/Lib/ruby/1.9.1/csv.rb:1818:in `
loop'
from C:/Program Files (x86)/IronRuby 1.1/Lib/ruby/1.9.1/csv.rb:1818:in `
shift'
from C:/myproject/myproject/myproject/Program.rb:3
I am using Ironruby 1.1.3
I am looking for the correct syntax to get a single line with the headers option.
I tested this in a different engine and this seems to be a bug in Ironruby
You could try this, mind the colsep, adapt it to what you have in your CSV files.
If you want to show the headers:
require 'csv'
path = "G:/documents/musicinfo"
Dir.glob("#{path}/**/*.csv").each {|file|
CSV.foreach(file, :col_sep => ';') do |row|
puts "#{file} => #{row}"
break
end
}
Gives as array:
G:/documents/musicinfo/album.csv => ["album_release_year", "album_id", "artist_id", "album"]
G:/documents/musicinfo/artist.csv => ["artist_id", "artist_name"]
G:/documents/musicinfo/Copy of all2.csv => ["album_release_year,album_id,track_id,artist_id,artist_name,duration,genre,track_popularity,disc_number,track_number,track,album"]
G:/documents/musicinfo/genres.csv => ["genreId", " genreNaam"]
G:/documents/musicinfo/songs.csv => ["album_id", " track_id", " artist_id", " track_popularity", "genre_id", "track"]
And, if you want to show the first datarow or keep it as CSV adapt the above with:
CSV.foreach(file, :col_sep => ';', :headers => true) do |row|
Which gives:
G:/documents/musicinfo/album.csv => 0000,10747312,11522976,Beyond Imagination (Bonus Track Version)
G:/documents/musicinfo/artist.csv => 10000004,Jimi Hendrix
G:/documents/musicinfo/Copy of all2.csv => "2008,12877382,24516577,10000004,Jimi Hendrix,05:39,Pop,9,16,1,10,Free spirit"
G:/documents/musicinfo/genres.csv => 1,Alternative
G:/documents/musicinfo/songs.csv => 12877382,24516577,10000004,9,16,Free spirit

Resources