Making RUBY Ocra work for library that requires include module - ruby

I have created a ruby executable in windows using OCRA. i am using it for few years now and works well no complains with it.
but today when i created and distributed a exe that contain Include module in the code it failed at the include module line.
is there a better way to write the code or compile the exe ?
in the below code the error occurs at include Mongo location. if i remove include module then the code does not work
require 'all the libs including mongo'
###############################################################
#### to insert the program parameters and the data to mongodb
###############################################################
def writedatatomongodb(toinsert, sname, dname, collname, lfile)
#Sampele params to insert {:command=>"get data", :servername=>"servname", :remotecommand=>"/user/home/somefile", :outputfile=>"filename123_YYYYMMDD.txt"}
include Mongo
#client = MongoClient.new(sname, 27017)
p "Copying parametrs to Mongodb"
##client = MongoClient.new('myservername', 27017)
#db = #client[dname]
#coll = #db[collname]
File.open(lfile, 'a'){ |f| f.puts "Copying params to Mongodb" }
id = #coll.insert(toinsert)
p "Copied parametrs to Mongodb"
rescue Exception => e
File.open(lfile, 'a'){ |f| f.puts "Error occured: #{e}" }
end

Related

How to use rescue when a LoadError is raised

I'm trying to implement a file dialog using Tk. This aspect has worked but my error checking isn't working.
Since this file dialog can only take certain extensions I made it raise a LoadError, but I also don't want the program to stop, I want it to reopen to allow the user to pick another file.
Each way I've tried has only ended in an infinite loop or a LoadError stopping the program.
My code is:
module FileExplorer
require 'tk'
require 'tkextlib/tile'
def self.fileDialog
TkClipboard.append(Tk.getOpenFile)
f = TkClipboard.get
begin
unless extenstionCheck(f)
raise LoadError, 'Please select a valid file type'
end
rescue LoadError
fileDialog
end
end
def self.extenstionCheck(file)
filetypes = ['.xlsx', '.xls', '.csv', '.xml']
type = File.extname(file)
true if filetypes.include?(file)
end
end
There's no need to use TkClipboard, nor to use an exception.
Did misspelling the word, 'extension' blind you to your nearby error of checking whether filetypes included file, instead of type?
Your program, minimally changed as follows, works for me:
module FileExplorer
require 'tk'
require 'tkextlib/tile'
def self.fileDialog
while true
f = Tk.getOpenFile
break if extension_okay?(f)
Tk.messageBox message: 'Please select a valid file type!', detail: "Selection was: #{f}"
end
f
end
def self.extension_okay?(file)
filetypes = ['.xlsx', '.xls', '.csv', '.xml']
type = File.extname(file)
filetypes.include?(type)
end
end
p FileExplorer.fileDialog
This is completely inappropriate (and unnecessary) use of LoadError.
Raised when a file required (a Ruby script, extension library, …)
fails to load.
Its a low level error that does not inherit from StandardError and is tied to Kernel#require.
Instead declare your own exceptions in your own namespace:
module FileExplorer
require 'tk'
require 'tkextlib/tile'
FileTypeError = Class.new(::StandardError)
def self.fileDialog
TkClipboard.append(Tk.getOpenFile)
f = TkClipboard.get
begin
unless extenstionCheck(f)
raise FileTypeError, 'Please select a valid file type'
end
rescue FileTypeError
fileDialog
end
end
def self.extenstionCheck(file)
filetypes = ['.xlsx', '.xls', '.csv', '.xml']
type = File.extname(file)
true if filetypes.include?(file)
end
end

Create a plugin that puts text in a .txt file

I am working on creating a plugin in Ruby.
On this moment I am unable to insert the coordinates, that are added to a Sketchup model, in a .txt file.
This is my code:
require 'sketchup.rb'
SKETCHUP_CONSOLE.show rescue Sketchup.send_action("showRubyPanel:")
$stdout = File.new('file.txt', 'w')
module HWmakemyownplug
def self.fileplug
model = Sketchup.active_model
#Make some coordinates.
coordinates = [[2,0,39],[0,0,1],[1,1,0]]
#Add the points in Sketchup. This works!
coordinates.each { |point| model.active_entities.add_cpoint(point) }
#Puts the coordinates to the textfile 'file.txt'. This doesn't work!
$stdout.puts(coordinates)
end #def self.fileplug
end #module makemyownplug
if (!file_loaded?(__FILE__))
#Add to the SketchUp tools menu
extensions_menu = UI.menu("Plugins")
extensions_menu.add_item("testtesttest") { HWmakemyownplug::fileplug }
# Let Ruby know we have loaded this file
file_loaded(__FILE__)
end
The coordinates have to be printed when I click on menu > plugins > testtesttest.
You forgot to close file after $stdout.puts(coordinates)
$stdout.close
Here is an example code for writing data to a JSON file instead of a simple text document.
The code can run outside of SketchUp for testing in the terminal. Just make sure to follow these steps...
Copy the code below and paste it on a ruby file (example: file.rb)
Run the script in terminal ruby file.rb or run with SketchUp.
The script will write data to JSON file and also read the content of JSON file.
The path to the JSON file is relative to the ruby file created in step one. If the script can't find the path it will create the JSON file for you.
module DeveloperName
module PluginName
require 'json'
require 'fileutils'
class Main
def initialize
path = File.dirname(__FILE__)
#json = File.join(path, 'file.json')
#content = { 'hello' => 'hello world' }.to_json
json_create(#content)
json_read(#json)
end
def json_create(content)
File.open(#json, 'w') { |f| f.write(content) }
end
def json_read(json)
if File.exist?(json)
file = File.read(json)
data_hash = JSON.parse(file)
puts "Json content: #{data_hash}"
else
msg = 'JSON file not found'
UI.messagebox(msg, MB_OK)
end
end
# # #
end
DeveloperName::PluginName::Main.new
end
end

how to share a rake variable in the code it invokes?

What I need is basically send a target argument and use it in my RSpec tests, e.g.:
$ rake unistall_and_run[test_spec.rb]
Rakefile:
desc 'uninstall app to run tests'
task :uninstall_and_run, [:arg] do |t, arg|
#note this, i will explain later
start_driver(fullReset: true)
oi = arg.to_s.split('"')[1]
file_dir = (project_home + '/spec/' + oi)
exec "rspec #{file_dir}"
end
start_driver is called on that line, but when I run the tests (exec "rspec ..."), it is called again and the args I passed is overwritten by the default (because its on RSpec config).
What I'd like to do is, on my RSpec file check if it was already called and don't run again.
Here is the start_driver method:
def start_driver(options= {})
if options.empty?
capabilities = caps
else
capabilities = caps(options)
end
$appium = Appium::Driver.new(caps: capabilities)
$browser = $appium.start_driver
Appium.promote_appium_methods RSpec::Core::ExampleGroup
end
So, i found a way to do it. Its not beautiful though. I save a file with the args I want when run rake:
desc 'uninstall app to run tests'
task :uninstall_and_run, [:arg] do |t, arg|
send_custom_caps(fullReset: true)
oi = arg.to_s.split('"')[1]
file_dir = (project_home + '/spec/' + oi)
exec "rspec #{file_dir}"
end
and the send_custom_caps method is:
def send_custom_caps(*opts)
file = File.new(custom_caps_file, "w+")
File.open(file, 'w') do |f|
f.write(opts)
end
end
now the ruby code itself (in this case, my spec config) will check if there is custom args before start_driver. Here is my custom start_driver method (which I renamed):
def start_appium_driver (options= {})
if options.empty?
get_caps
if $custom_args
capabilities = caps($custom_args)
else
capabilities = caps
end
else
capabilities = caps(options)
end
$appium = Appium::Driver.new(caps: capabilities)
$browser = $appium.start_driver
Appium.promote_appium_methods RSpec::Core::ExampleGroup
end
and get_caps
def get_caps
if File.exist?(custom_caps_file) #$custom_args
file = File.read(custom_caps_file)
$custom_args = eval(file)
File.delete (custom_caps_file)
end
$custom_args unless $custom_args.defined?
end
probably this is not the best solution, but it is working ok for me :)

No such file or directory error in service

I am a newbie to ruby and got stuck into one of the issues with the windows service I created (code is below). When the service runs, I get an error in test log that there is notsuch file or directory and it does not find any path to the logs with name QaTaTestExe.log.xml. This is the error I see in file.
***Daemon failure 2013-07-28 16:29:28 -0400 err=No such file or directory
However when I tried the code (which is after while running? ) in separate class it works. Am I missing anything in my configuration since the error is regarding Daemon?
LOG_FILE = 'C:\\test.log'
require "rubygems"
begin
require 'win32/daemon'
include Win32
class Daemon
def service_main
while running?
testresultpath = "Z:/Windows 2008 R2 - Exchange 2010 - Search"
file_path s =[]
Find.find(testresultpath) do |path|
file_paths << path if path =~ /.*\QaTaTestExe.log.xml$/
File.open("c:\\test.log", "a"){ |f| f.puts(path)}
end
sleep 30
File.open("c:\\test.log", "a"){ |f| f.puts "Service is running #{Time.now}" }
end
end
def service_stop
File.open("c:\\test.log", "a"){ |f| f.puts "***Service stopped #{Time.now}" }
exit!
end
end
Daemon.mainloop
rescue Exception => err
File.open(LOG_FILE,'a+'){ |f| f.puts " ***Daemon failure #{Time.now} err=#{err} " }
raise
end

How do I query a MS Access database table, and export the information to Excel using Ruby and win32ole?

I'm new to Ruby, and I'm trying to query an existing MS Access database for information for a report. I want this information stored in an Excel file. How would I do this?
Try one of these:
OLE:
require 'win32ole'
class AccessDbExample
#ado_db = nil
# Setup the DB connections
def initialize filename
#ado_db = WIN32OLE.new('ADODB.Connection')
#ado_db['Provider'] = "Microsoft.Jet.OLEDB.4.0"
#ado_db.Open(filename)
rescue Exception => e
puts "ADO failed to connect"
puts e
end
def table_to_csv table
sql = "SELECT * FROM #{table};"
results = WIN32OLE.new('ADODB.Recordset')
results.Open(sql, #ado_db)
File.open("#{table}.csv", 'w') do |file|
fields = []
results.Fields.each{|f| fields << f.Name}
file.puts fields.join(',')
results.GetRows.transpose.each do |row|
file.puts row.join(',')
end
end unless results.EOF
self
end
def cleanup
#ado_db.Close unless #ado_db.nil?
end
end
AccessDbExample.new('test.mdb').table_to_csv('colors').cleanup
ODBC:
require 'odbc'
include ODBC
class AccessDbExample
#obdc_db = nil
# Setup the DB connections
def initialize filename
drv = Driver.new
drv.name = 'AccessOdbcDriver'
drv.attrs['driver'] = 'Microsoft Access Driver (*.mdb)'
drv.attrs['dbq'] = filename
#odbc_db = Database.new.drvconnect(drv)
rescue
puts "ODBC failed to connect"
end
def table_to_csv table
sql = "SELECT * FROM #{table};"
result = #odbc_db.run(sql)
return nil if result == -1
File.open("#{table}.csv", 'w') do |file|
header_row = result.columns(true).map{|c| c.name}.join(',')
file.puts header_row
result.fetch_all.each do |row|
file.puts row.join(',')
end
end
self
end
def cleanup
#odbc_db.disconnect unless #odbc_db.nil?
end
end
AccessDbExample.new('test.mdb').table_to_csv('colors').cleanup
Why do you want to do this? You can simply query your db from Excel directly. Check out this tutorial.
As Johannes said, you can query the database from Excel.
If, however, you would prefer to work with Ruby...
You can find info on querying Access/Jet databases with Ruby here.
Lots of info on automating Excel with Ruby can be found here.
David

Resources