Can you create inputbox with Ruby? - ruby

I have used VBScript in the past for QTP and I could use the input box function to display a pop up window.
I am wondering if there is a way to do this with Ruby? I need a popup that will allow the user to input some information before the WATIR script executes.
I looked around StackOverflow but didn't see anything.

Here an example of how to get the messagebox from vbscript in Ruby, i'll try to get the inputbox in the same way
require "Win32API"
message = "This is a sample Windows message box generated using Win32API"
title = "Win32API from Ruby"
api = Win32API.new('user32','MessageBox',['L', 'P', 'P', 'L'],'I')
api.call(0,message,title,0)

Maybe this example code helps you (win32 only):
require 'win32ole'
def inputbox( message, title="Message from #{__FILE__}" )
vb_msg = %Q| "#{message.gsub("\n",'"& vbcrlf &"')}"|
vb_msg.gsub!( "\t", '"& vbtab &"' )
vb_msg.gsub!( '&""&','&' )
vb_title = %Q|"#{title}"|
# go!
sc = WIN32OLE.new( "ScriptControl" )
sc.language = "VBScript"
sc.eval(%Q|Inputbox(#{vb_msg}, #{vb_title})|)
#~ sc.eval(%Q|Inputbox(#{vb_msg}, #{vb_title}, aa,hide)|)
end
def popup(message)
wsh = WIN32OLE.new('WScript.Shell')
wsh.popup(message, 0, __FILE__)
end
str = "a | does not break it...\n\nOne\n\tTwo tabbed\nThree..."
res = inputbox( str, "demonstration | title")
popup %Q|When asked\n\n"#{str}"\n\nyou answered:\n#{res}|
This results in:
It follows a popup box with.
See also http://rubyonwindows.blogspot.com/2007/04/ruby-excel-inputbox-hack.html

Since i can't find an inputbox api for windows here is what i do most of the time if i need some simple dialog. Unlike red shoes it is just a gem so easy to install.
require 'green_shoes'
Shoes.app{
e = edit_line
button("Click me!"){alert("You entered." + e.text)}
}

Ruby is a programing/scripting language, so on it's own it doesn't do any kind of GUI or Graphics related stuff. That being said there are quite a few projects and frameworks that use Ruby to accomplish the type of thing you are looking for. The big ones are Ruby on Rails that uses Ruby to create web applications, and Shoes which is for creating computer applications.
There is also this question
What's the best/easiest GUI Library for Ruby?

I would suggest shoes, it's a cross-platform toolkit for writing graphical apps.
I used it and it's pretty cool, you can do something like:
Shoes.app :width => 300, :height => 200 do
stack do
edit_line :width => 400
end
end

Related

Reading a Gmail Message with ruby-gmail

I am looking for an instance method from the ruby-gmail gem that would allow me to read either:
the body
or
subject
of a Gmail message.
After reviewing the documentation, found here, I couldn't find anything!?
There is a .message instance method found in the Gmail::Message class section; but it only returns, for lack of a better term, email "mumbo-jumbo," for the body.
My attempt:
#!/usr/local/bin/ruby
require 'gmail'
gmail = Gmail.connect('username', 'password')
emails = gmail.inbox.emails(:from => 'someone#mail.com')
emails.each do |email|
email.read
email.message
end
Now:
email.read does not work
email.message returns that, "mumbo-jumbo," mentioned above
Somebody else asked this question on SO but didn't get an answer.
This probably isn't exactly the answer to your question, but I will tell you what I have done in the past. I tried using the ruby-gmail gem but it didn't do what I wanted it to do in terms of reading a message. Or, at least, I couldn't get it to work. Instead I use the built-in Net::IMAP class to log in and get a message.
require 'net/imap'
imap = Net::IMAP.new('imap.gmail.com',993,true)
imap.login('<username>','<password>')
imap.select('INBOX')
subject_id = search_mail(imap, 'SUBJECT', '<mail_subject>')
subject_message = imap.fetch(subject_id,'RFC822')[0].attr['RFC822']
mail = Mail.read_from_string subject_message
body_message = mail.html_part.body
From here your message is stored in body_message and is HTML. If you want the entire email body you will probably need to learn how to use Nokogiri to parse it. If you just want a small bit of the message where you know some of the surrounding characters you can use a regex to find the part you are interested in.
I did find one page associated with the ruby-gmail gem that talks about using ruby-gmail to read a Gmail message. I made a cursory attempt at testing it tonight but apparently Google upped the security on my account and I couldn't get in using irb without tinkering with my Gmail configuration (according to the warning email I received). So I was unable to verify what is stated on that page, but as I mentioned my past attempts were unfruitful whereas Net::IMAP works for me.
EDIT:
I found this, which is pretty cool. You will need to add in
require 'cgi'
to your class.
I was able to implement it in this way. After I have my body_message, call the html2text method from that linked page (which I modified slightly and included below since you have to convert body_message to a string):
plain_text = html2text(body_message)
puts plain_text #Prints nicely formatted plain text to the terminal
Here is the slightly modified method:
def html2text(html)
text = html.to_s.
gsub(/( |\n|\s)+/im, ' ').squeeze(' ').strip.
gsub(/<([^\s]+)[^>]*(src|href)=\s*(.?)([^>\s]*)\3[^>]*>\4<\/\1>/i,
'\4')
links = []
linkregex = /<[^>]*(src|href)=\s*(.?)([^>\s]*)\2[^>]*>\s*/i
while linkregex.match(text)
links << $~[3]
text.sub!(linkregex, "[#{links.size}]")
end
text = CGI.unescapeHTML(
text.
gsub(/<(script|style)[^>]*>.*<\/\1>/im, '').
gsub(/<!--.*-->/m, '').
gsub(/<hr(| [^>]*)>/i, "___\n").
gsub(/<li(| [^>]*)>/i, "\n* ").
gsub(/<blockquote(| [^>]*)>/i, '> ').
gsub(/<(br)(| [^>]*)>/i, "\n").
gsub(/<(\/h[\d]+|p)(| [^>]*)>/i, "\n\n").
gsub(/<[^>]*>/, '')
).lstrip.gsub(/\n[ ]+/, "\n") + "\n"
for i in (0...links.size).to_a
text = text + "\n [#{i+1}] <#{CGI.unescapeHTML(links[i])}>" unless
links[i].nil?
end
links = nil
text
end
You also mentioned in your original question that you got mumbo-jumbo with this step:
email.message *returns mumbo-jumbo*
If the mumbo-jumbo is HTML, you can probably just use your existing code with this html2text method instead of switching over to Net::IMAP as I had discussed when I posted my original answer.
Nevermind, it's:
email.subject
email.body
silly me
ok, so how do I get the body in "readable" text? without all the encoding stuff and html?
Subject, text body and HTML body:
email.subject
if email.message.multipart?
text_body = email.message.text_part.body.decoded
html_body = email.message.html_part.body.decoded
else
# Only multipart messages contain a HTML body
text_body = email.message.body.decoded
html_body = text
end
Attachments:
email.message.attachments.each do |attachment|
path = "/tmp/#{attachment.filename}"
File.write(path, attachment.decoded)
# The MIME type might be useful
content_type = attachment.mime_type
end
require 'gmail'
gmail = Gmail.connect('username', 'password')
emails = gmail.inbox.emails(:from => 'someone#mail.com')
emails.each do |email|
puts email.subject
puts email.text_part.body.decoded
end

Ruby: gets.chomp with default value

Is there some simple way how to ask for a user input in Ruby WHILE providing a default value?
Consider this code in bash:
function ask_q {
local PROMPT="$1"
local DEF_V="$2"
read -e -p "$PROMPT" -i "$DEF_V" REPLY
echo $REPLY
}
TEST=$(ask_q "Are you hungry?" "Yes")
echo "Answer was \"$TEST\"."
Can you achieve similar behaviour with Ruby's gets.chomp?
function ask_q(prompt, default="")
puts prompt
reply = gets.chomp() # ???
return reply
def
reply = ask_q("Are you hungry?", "Yes")
I understand I can sort replicate the functionality in Ruby this way ...
def ask_q(prompt, default="")
default_msg = (default.to_s.empty?) ? "" : "[default: \"#{default}\"]"
puts "${prompt} ${default}"
reply = gets.chomp()
reply = (default.to_s.empty?) ? default : reply
return reply
end
... but it does not seem very pretty. I also need to show the default value manually and the user needs to retype it in the prompt line, if he wants to use modified version of it (say yes! instead of yes).
I'm starting with Ruby now, so there may be a lot of syntax mistakes and I also may be missing something obvious ... Also, I googled a lot but surprisingly found no clue.
TL; DR
To make the question clearer, this is what you should see in terminal and what I am able to achieve in bash (and not in Ruby, so far):
### Terminal output of `reply=ask_q("Are you hungry?" "Yes")`
$ Are you hungry?
$ Yes # default editable value
### Terminal output of `reply=ask_q("What do you want to eat?")`
$ What do you want to eat?
$ # blank line waiting for user input, since there is no second parameter
And the actual situation: I am building bootstrap script for my web apps. I need to provide users with existing configuration data, that they can change if needed.
### Terminal output of `reply=ask_q("Define name of database." "CURR_DB_NAME")`
I don't think it's that fancy functionality, that would require switch to GUI app world.
And as I've said before, this is quite easily achievable in bash. Problem is, that other things are pure pain (associative arrays, no return values from functions, passing parameters, ...). I guess I just need to decide what sucks the least in my case ...
You need to do one of two things:
1) Create a gui program.
2) Use curses.
Personally, I think it's a waste of time to spend any time learning curses. Curses has even been removed from the Ruby Standard Library.
A GUI program:
Here is what a gui app looks like using the Tkinter GUI Framework:
def ask_q(prompt, default="")
require 'tk'
root = TkRoot.new
root.title = "Your Info"
#Display the prompt:
TkLabel.new(root) do
text "#{prompt}: "
pack("side" => "left")
end
#Create a textbox that displays the default value:
results_var = TkVariable.new
results_var.value = default
TkEntry.new(root) do
textvariable results_var
pack("side" => "left")
end
user_input = nil
#Create a button for the user to click to send the input to your program:
TkButton.new(root) do
text "OK"
command(Proc.new do
user_input = results_var.value
root.destroy
end)
pack("side" => "right", "padx"=> "50", "pady"=> "10")
end
Tk.mainloop
user_input
end
puts ask_q("What is your name", "Petr Cibulka")
Calling a function in a bash script from ruby:
.../bash_programs/ask_q.sh:
#!/usr/bin/env bash
function ask_q {
local QUESTION="$1"
local DEFAULT_ANSWER="$2"
local PROMPT="$QUESTION"
read -p "$PROMPT $DEFAULT_ANSWER" USERS_ANSWER #I left out the -i stuff, because it doesn't work for my version of bash
echo $USERS_ANSWER
}
ruby_prog.rb:
answer = %x{
source ../bash_programs/ask_q.sh; #When ask_q.sh is not in a directory in your $PATH, this allows the file to be seen.
ask_q 'Are you Hungry?' 'Yes' #Now you can call functions defined inside ask_q.sh
}
p answer.chomp #=> "Maybe"
Using curses:
require 'rbcurse/core/util/app'
def help_text
<<-eos
Enter as much help text
here as you want
eos
end
user_answer = "error"
App.new do #Ctrl+Q to terminate curses, or F10(some terminals don't process function keys)
#form.help_manager.help_text = help_text() #User can hit F1 to get help text (some terminals do not process function keys)
question = "Are You Hungry?"
default_answer = "Yes"
row_position = 1
column_position = 10
text_field = Field.new(#form).
name("textfield1").
label(question).
text(default_answer).
display_length(20).
bgcolor(:white).
color(:black).
row(row_position).
col(column_position)
text_field.cursor_end
text_field.bind_key(13, 'return') do
user_answer = text_field.text
throw :close
end
end
puts user_answer

Ruby shoes, para.cursor method

My question is concerning the "para" object. Where can I look up all the methods para has? I tried the shoesrb.com manual but all it says is that para is used to render text. I also tried #shoes at Freenode, but no one answered. Seems that no one is online.
I ask because I don't understand what the pounded (###) line does.
str, t = "", nil
Shoes.app :height => 500, :width => 450 do
background rgb(77, 77, 77)
stack :margin => 10 do
para span("TEXT EDITOR", :stroke => red, :fill => white), " * USE ALT-Q TO QUIT", :stroke => white
end
stack :margin => 10 do
t = para "", :font => "Monospace 12px", :stroke => white
t.cursor = -1 ####### I don't understand this line
end
keypress do |k|
case k
when String
str += k
when :backspace
str.slice!(-1)
when :tab
str += " "
when :left ### This is the part I'm interested in
#### Can you suggest a method to put in here. It moves the cursor to the left.
when :alt_q
quit
when :alt_c
self.clipboard = str
when :alt_v
str += self.clipboard
end
t.replace str
end
end
Does the para class have a cursor method? The official documentation has no answer.
I am trying to extend this into a simple text editor but I can't understand how to move the cursor.
I am a novice programer and new to Ruby as well.
Furthermore, where do the Shoes programmers hang out? I tried the mailing list, apparently it's out of service. Is there are specific forum or a different mailing list?
thanks for trying out Shoes.
Yes, Red Shoes a.k.a. Shoes 3 apparently has a cursor method that lets you set the position of the cursor. It's undocumented though, I had to look up in the sources. Your milage may vary using it.
The Shoes mailing list is definitely alive and active. Just send a message to shoes#librelist.com and you should automatically be signed up. That would be the best channel for help on Shoes, for the rest communication happens mostly through Github issues.

Rally: How do I access custom created fields via the Web Services API

I have read through the Web Services site at http://developer.rallydev.com/help/
The basic issue I have is that I am trying to update custom created fields in Rally from a Ruby script and I do not know the format to use. The Rally Devs said this was possible and directed me to post here as they do not support users with such things.
I am wondering if anyone else has been able to do this. I can get the defect, but the debug info has not given me any clues as to where these custom fields may be lurking. Thanks in advance for your help and please let me know if you need any additional information. The simple code I have right now is this:
#!/usr/bin/ruby
require 'rubygems'
require 'rally_rest_api'
defect = "DE677"
logger = Logger.new("debug-rally.txt")
logger.level = Logger::DEBUG
rally = RallyRestAPI.new(:username => "hidden",
:password => "hidden",
:logger => logger,
:version => 1.34)
result = rally.find(:defect) { equal :formattedid, defect }
if result.page_length == 0
puts "The defect "+defect+" was not found"
elsif result.page_length == 1
puts "Found it"
res_array = result.results
thedefect = res_array.at(0)
puts thedefect.state
puts thedefect.requirement.defects
else
puts "Returned more than one result"
puts result.page_length
res_array = result.results
for i in res_array
puts i
end
end
EDIT:It was actually staring me right in the face. When I checked the debug log again they were in the xml. For instance in the UI there was a custom field called fu and in the resulting xml it was there as bar.
There is a display name and a name property when you create it. In your example my guess is fu is your display name and bar is the name.

Word Automation using WIN32OLE

I am trying to insert an image (jpg) in to a word document and the Selection.InlineShapes.AddPicture does not seem to be supported by win32old or I am doing something wrong. Has anyone had any luck inserting images.
You can do this by calling the Document.InlineShapes.AddPicture() method.
The following example inserts an image into the active document, before the second sentence.
require 'win32ole'
word = WIN32OLE.connect('Word.Application')
doc = word.ActiveDocument
image = 'C:\MyImage.jpg'
range = doc.Sentences(2)
params = { 'FileName' => image, 'LinkToFile' => false,
'SaveWithDocument' => true, 'Range' => range }
pic = doc.InlineShapes.AddPicture( params )
Documentation on the AddPicture() method can be found here.
Additional details on automating Word with Ruby can be found here.
This is the answer by David Mullet and can be found here
Running on WinXP, Ruby 1.8.6, Word 2002/XP SP3, I recorded macros and translated them, as far as I could understand them, into this:
require 'win32ole'
begin
word = WIN32OLE::new('Word.Application') # create winole Object
doc = word.Documents.Add
word.Selection.InlineShapes.AddPicture "C:\\pictures\\some_picture.jpg", false, true
word.ChangeFileOpenDirectory "C:\\docs\\"
doc.SaveAs "doc_with_pic.doc"
word.Quit
rescue Exception => e
puts e
word.Quit
ensure
word.Quit unless word.nil?
end
It seems to work. Any use?

Resources