Geektool and TextMate Error - ruby

I am giving myself little projects during the winter break, and am trying to write little geektool scripts I can use for my desktop. I wrote this for ruby and it works in terminal, but when I run it in textmate I get a host is down error, and when I place it in geektool it will not run.
#!/usr/bin/ruby
require 'open-uri'
require 'nokogiri'
def fetch_xml()
open("http://weather.yahooapis.com/forecastrss?w=2424766&u=f")
end
def parse_xml()
source = Nokogiri::XML(fetch_xml)
location = source.xpath("//yweather:location")
condition = source.xpath("//item//yweather:condition")
forecast = source.xpath("//item//yweather:forecast")
[location[0]['city'], location[0]['region'], condition[0]['temp'].to_i, condition[0]['text'], forecast[0]['high'], forecast[0]['low']]
end
def display_weather()
result = parse_xml()
print "#{result}\n"
end
display_weather
It runs in terminal and gives me the correct output: ["Houston", "TX", 64, "Cloudy", "69", "63"]
But like I mentioned earlier, it will not run within textmate, and nothing shows up in geektool. Thanks in advance for any help.

Related

Launching Sinatra at Terminal stays blank

I was trying to run Sinatra and Ruby in my MacBook, and all was working fine. Then, suddenly, I tried again and it just stays like this:
I can't access to localhost or anything. I don't know what to do. I've been researching for hours. Please, help me.
This is what my ruby code looks like:
require 'sinatra'
gets '/ejemplo1' do
puts 'Hello World'
end
Seems to be a typo. Should be get and not gets.
require 'sinatra'
get '/ejemplo1' do
puts 'Hello World'
end
Additional info:
gets in ruby is a way to get user input:
name = gets
puts "Your name is #{name}"
Like mentioned by #Norly Canarias you should use get for routing in sinatra. Moreover if you use puts statement in get block it will print only in terminal when you run your code not in webpage when you access localhost. Correct way to make it display in webpage is given below
require 'sinatra'
get '/ejemplo1' do
'Hello World'
end

Ruby Shoes execute another ruby program

I've got a small shoes (3.3.3) program and a small ruby console program with selenium (3.4.4).
If I open the selenium console program directly everything works fine, but if I want to open it via "exec("")" through shoes, it breaks and closes.
I thought the error is the webdriver, so I've written a simple console program with some easy "puts" output and shoes displays the console and the output.
The thing is... the selenium program worked yesterday and I can't find the problem, why it doesn't now.
The simplified shoes code looks like this:
Shoes.app(width: 200, height: 200, resizable: false){
button("GO", width: 200) do
exec('ruby data/test.rb')
end
}
Here comes the simple selenium-webdriver code named "test.rb":
require 'selenium-webdriver'
Selenium::WebDriver::PhantomJS.driver_path =
"driver/phantomjs/bin/phantomjs.exe"
browser = Selenium::WebDriver.for :phantomjs
wait = Selenium::WebDriver::Wait.new(:timeout => 15)
browser.navigate.to
"http://www.accuweather.com/de/de/heinsberg/52525/weather-forecast/174475"
wetterElement = browser.find_element(:id, "wrap-forecast-feed")
#wetterData = wetterElement.text.gsub(/\n/, ',').split(",")
puts #wetterData[1]
gets.chomp
Shoes gives me the following error message for a few msecs before it breaks:
So I looked it up, and found this code snippet:
def assert_file(path)
return if File.file? path
raise Error::WebDriverError, "not a file: #{path.inspect}"
end
def assert_executable(path)
assert_file(path)
return if File.executable? path
raise Error::WebDriverError, "not executable: #{path.inspect}"
end
I really have no idea...
Thank you in advance.
Got it ...
The folder with the shoes app was UTF-8 formatted. Simply changed the name and it worked.

Can't get File Tail working

Out of curiosity I tried file-tail ruby library to see how it works with ruby code. But, the code doesn't seem to be working.
Here is what I tired(logger.rb):
$:.unshift File.dirname(__FILE__)
filename = 'logger.log'
require "file-tail"
File.open(filename) do |log|
log.extend(File::Tail)
log.interval = 10
log.backward(10)
log.tail { |line| puts line }
end
My logger.log file is in the same directory. Now, when I run: $ ruby logger.rb I see the last 10 lines from my log, but when I open logger.log file append some log data to it, the console doesn't show any progress. I mean it doesn't output the new log I appended.
I thought there may be in an issue with this. So, I tried inheriting and including the File::Tail in the inherited class, like this:
$:.unshift File.dirname(__FILE__)
filename = 'logger.log'
require "file-tail"
class FileTail < File
require "file-tail"
include File::Tail
end
log = FileTail.new(filename)
log.interval = 10
log.backward(10)
log.tail { |line| print line }
However this behaves the same way!!
Any pointers?
I am running on MAC OC X 10.8.5 with ruby-2.0.0-p353 installed.
Also, please let me know if anybody has implemented web version of tail in Ruby?
My Bad. This works when I closed all streams of my logger file. I'd opened the file in my ruby code but, didn't close the file stream. Maybe that's why I didn't see any log output on my console using the file-tail.
So, make sure you close all streams of the log/text file you're running with file-tail program.

how to write selenium ruby webdriver test results from Ruby terminal to output files

Currently, I'm running all selenium scripts in my test suite (written by Selenium Ruby Webdriver) at one time by using rake gem in "Start Command Prompt with Ruby" terminal.
To do this I have to create a file with name "rakefile.rb" with below content and just call "rake" in my terminal: (I have known this knowledge based on the guide of a person in my previous post how to export results when running selenium ruby webdriver scripts to output files from command prompt ruby window).
task :default do
$stdout = File.new('console.out', 'w')
$stdout.sync = true
FileList['test*.rb'].each { |file|
begin
ruby file
rescue
puts "The following tests reported unexpected behavior:"
puts "#{file} \n"
end
}
end
However, I do not know how to modify "rakefile.rb" to be able to export the content of executing each failed tests (that being displayed on my Terminal) to each output file ? It means that I expect the content of executing each my script will be written to output files instead of displaying on my Ruby terminal (ex: when I'm running the test script "test_GI-1.rb", then the content of executing this script will be written to an output file "test_GI-1.rb.out" instead of showing in my Terminal.
I modified my "rakefile.rb" to something like ruby file >> test.rb.out, but it does not work at all (this thing only works when I type directly the thing like ruby test.rb >> output.out on my Ruby Terminal). Anybody please guide me a way. Thanks so much.
I have not tried this out, but I guess this should work
task :default do
FileList['test*.rb'].each { |file|
begin
system("ruby #{file} > #{file}.log")
rescue
puts "The following tests reported unexpected behavior:"
puts "#{file} \n"
end
}
end
Based on new requirements -
UPDATE
task :default do
logfile.new("console.out", "w")
FileList['test*.rb'].each { |file|
begin
system("ruby #{file} > #{file}.log")
rescue
logfile.puts("The following tests reported unexpected behavior:")
logfile.puts("#{file} \n")
end
}
end

How do I drop to the IRB prompt from a running script?

Can I drop to an IRB prompt from a running Ruby script?
I want to run a script, but then have it give me an IRB prompt at a point in the program with the current state of the program, but not just by running rdebug and having a breakpoint.
Pry (an IRB alternative) also lets you do this, in fact it was designed from the ground up for exactly this use case :)
It's as easy as putting binding.pry at the point you want to start the session:
require 'pry'
x = 10
binding.pry
And inside the session:
pry(main)> puts x
=> 10
Check out the website: http://pry.github.com
Pry let's you:
drop into a session at any point in your code
view method source code
view method documentation (not using RI so you dont have to pre-generate it)
pop in and out of different contexts
syntax highlighting
gist integration
view and replay history
open editors to edit methods using edit obj.my_method syntax
A tonne more great and original features
you can use ruby-debug to get access to irb
require 'rubygems'
require 'ruby-debug'
x = 23
puts "welcome"
debugger
puts "end"
when program reaches debugger you will get access to irb.
apparently it requires a chunk of code to drop into irb.
Here's the link (seems to work well).
http://jameskilton.com/2009/04/02/embedding-irb-into-your-ruby-application
require 'irb'
module IRB
def self.start_session(binding) # call this method to drop into irb
unless #__initialized
args = ARGV
ARGV.replace(ARGV.dup)
IRB.setup(nil)
ARGV.replace(args)
#__initialized = true
end
workspace = WorkSpace.new(binding)
irb = Irb.new(workspace)
#CONF[:IRB_RC].call(irb.context) if #CONF[:IRB_RC]
#CONF[:MAIN_CONTEXT] = irb.context
catch(:IRB_EXIT) do
irb.eval_input
end
end
end
This feature is available from Ruby 2.4. You can just use binding.irb
E.g.
require 'irb'
a = 10
binding.irb
puts a
If you run above code, you will get irb console, so that you can inspect values of local variables and anything else that is in scope.
Source: http://blog.redpanthers.co/new-binding-irb-introduced-ruby-2-4/
Ruby commit: https://github.com/ruby/ruby/commit/493e48897421d176a8faf0f0820323d79ecdf94a
Just add this line to where you want the breakpoint:
require 'ruby-debug';debugger
but i suggest use pry instead of irb, which is super handy, insert the following line instead:
require 'pry'; binding.pry
I'm quite late to the game but if you're loading a script from within irb/pry already, a simple raise also works to pop you back out to the irb/pry prompt. I use this quite often when writing one off scripts within the rails console.

Resources