Gareth Simpson
Gareth Simpson

Reputation: 37701

Open the default browser in Ruby

In Python, you can do this:

import webbrowser
webbrowser.open_new("http://example.com/")

It will open the passed in url in the default browser

Is there a ruby equivalent?

Upvotes: 62

Views: 29360

Answers (9)

Felix
Felix

Reputation: 4716

You can use the 'os' gem: https://github.com/rdp/os to let your operating system (in the best case you own your OS, meaning not OS X) decide what to do with an URL.

Typically this will be a good choice.

require 'os'

system(OS.open_file_command, 'https://stackoverflow.com')
# ~ like `xdg-open stackoverflow.com` on most modern unixoids,
# but should work on most other operating systems, too.

Note On windows, the argument(s?) to system need to be escaped, see comment section. There should be a function in Rubys stdlib for that, feel free to add it to the comments and I will update the answer.

Upvotes: 3

Ryan McGeary
Ryan McGeary

Reputation: 240134

Cross-platform solution:

First, install the Launchy gem:

$ gem install launchy

Then, you can run this:

require 'launchy'

Launchy.open("http://stackoverflow.com")

Upvotes: 93

user1931928
user1931928

Reputation: 351

This should work on most platforms:

link = "Insert desired link location here"
if RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/
  system "start #{link}"
elsif RbConfig::CONFIG['host_os'] =~ /darwin/
  system "open #{link}"
elsif RbConfig::CONFIG['host_os'] =~ /linux|bsd/
  system "xdg-open #{link}"
end

Upvotes: 35

damage3025
damage3025

Reputation: 81

Linux-only solution

system("xdg-open", "http://stackoverflow.com/")

Upvotes: 8

Ryan McGeary
Ryan McGeary

Reputation: 240134

Mac-only solution:

system("open", "http://stackoverflow.com/")

or

`open http://stackoverflow.com/`

Upvotes: 32

James Baker
James Baker

Reputation: 6048

Simplest Win solution:

`start http://www.example.com`

Upvotes: 9

palmsey
palmsey

Reputation: 5832

This also works:

system("start #{link}")

Upvotes: 4

Zsolt Botykai
Zsolt Botykai

Reputation: 51693

If it's windows and it's IE, try this: http://rubyonwindows.blogspot.com/search/label/watir also check out Selenium ruby: http://selenium.rubyforge.org/getting-started.html

HTH

Upvotes: 0

Ken
Ken

Reputation: 2092

Windows Only Solution:

require 'win32ole'
shell = WIN32OLE.new('Shell.Application')
shell.ShellExecute(...)

Shell Execute on MSDN

Upvotes: 3

Related Questions