How can I use Ruby to check if a domain exists? - ruby

Something along the lines of:
def domain_exists?(domain)
# perform check
# return true|false
end
puts "valid!" if domain_exists?("example.com")

require 'socket'
def domain_exists?(domain)
begin
Socket.gethostbyname(domain)
rescue SocketError
return false
end
true
end

If you want to check whether a domain is registered or not, then you need to perform a Whois query.
http://www.ruby-whois.org/

With ruby-whois is pretty easy:
Install gem and require.
a = Whois.whois("google.com")
a.available?
=> false
There is also a CLI bundled if you install it via ruby gems: ruby-whois
web page at: ruby-whois.org

You could shell out to nslookup like this:
`nslookup #{domain}`
and parse the results as text with regexes etc.
Or you can use the Socket class, specifically Socket.getaddrinfo. See previous StackOverflow answer on this very question.

Related

Customising IRB console for gem

I'd like to extend the default console application that is built as standard with bundle gem by applying some of the IRB config options.
Looking at the documentation, I can see that it should be possible for instance to change the prompt, and this works fine on an interactive session. For example I can play with the displayed prompt like this:
2.1.4 :001 > conf.prompt_mode=:SIMPLE
=> :SIMPLE
>>
?> conf.prompt_mode=:DEFAULT
=> :DEFAULT
irb(main):004:0>
However, I cannot find how to translate this into syntax for use in the console app. For example this script:
require 'irb'
IRB.conf[:PROMPT_MODE] = :SIMPLE
IRB.start
Just starts with the generic configured prompt:
2.1.4 :001 >
I have spent some time trying to find an example use of IRB for a custom repl without loading global defaults, but not found anything I can copy from.
I can see that the undocumented method IRB.setup has something to do with this, it is setting all the config somehow. Is my only option to write my own version of IRB.start that applies my desired config after calling IRB.setup, or is there support for what I want to do built-in but not documented in standard location?
E.g. the following works, but I feel it's a bit heavy handed extending IRB module this way (and also prone to failing if IRB internals change).
require 'irb'
def IRB.custom_start custom_conf = {}
STDOUT.sync = true
IRB.setup(nil)
custom_conf.each do |k,v|
IRB.conf[k] = v
end
if #CONF[:SCRIPT]
irb = IRB::Irb.new(nil, #CONF[:SCRIPT])
else
irb = IRB::Irb.new
end
#CONF[:IRB_RC].call(irb.context) if #CONF[:IRB_RC]
#CONF[:MAIN_CONTEXT] = irb.context
trap("SIGINT") do
irb.signal_handle
end
begin
catch(:IRB_EXIT) do
irb.eval_input
end
ensure
irb_at_exit
end
end
IRB.custom_start :PROMPT_MODE => :SIMPLE
You can apply custom configurations in two ways.
The first one is to use irbrc file. It may be tricky in building console application (calling IRB.start from the ruby file instead of irb from the console).
The second one is the approach that you have described in the post. You can write your own IRB::start method based on the original one. There are exactly the same potential issues as in using undocumented API - it can break in the future with newer versions of irb.
You should think if you really need to build a console application on the top of irb. For example you can solve this problem using Pry. It allows to define configuration before starting interactive session.
require 'irb'
IRB.conf[:PROMPT_MODE] = :SIMPLE
IRB.start
The approach above doesn't work because conf[:PROMPT_MODE] gets over-riden in a method called IRB.init_config here
When IRB.start is called, it calls IRB.setup which in turn calls the method IRB.init_config -- which over-rides conf[:PROMPT_MODE] setting.
Here is one approach which solves the problem (relies on internal knowledge of the implementation).
require 'irb'
module IRB
singleton_class.send(:alias_method, :old_setup, :setup)
def IRB.setup(ap_path)
IRB.old_setup(ap_path)
conf[:PROMPT_MODE] = :SIMPLE
end
end
IRB.start

How to know whether a FileUtils command was successful?

I don't see any return value from FileUtils commands.
I'd like to do something like:
really=(gets.chomp=="y")
if really
success = FileUtils.rm_rf "./PROJECT_#{#name}" #does not work
end
puts "./PROJECT_#{#name} deleted" if success
I read the documentation for FileUtils, and also read a "Getting executed command from ruby FileUtils", but I cannot figure how to use the answer.
According to the documentation ( http://ruby-doc.org/stdlib-1.9.3/libdoc/fileutils/rdoc/FileUtils.html#method-c-rm_rf ) calls to #rm_rf will not echo anything relevant to the task they are taking. #rm_rf actually calls #rm_r with option :force => true. This options enables the method to ignore the StandardError Exception (which would then communicate you something about the operation or why it is not working). Now, back to why it is failing. As somebody already commented, try with the option :secure => true. More info about this here: http://ruby-doc.org/stdlib-1.9.3/libdoc/fileutils/rdoc/FileUtils.html#method-c-remove_entry_secure . This is probably a permission issue.
I think you need to check the return value:
irb(main):006:0> FileUtils.rm_rf 'test'
=> ["test"]
irb(main):007:0>
and check if an exception is raised in case of the directory doesn't exist.
If you need the return value, maybe your only option is to run the command inside ruby, please take a look at this blog post.

RSpec. How to color the piped or redirected output?

In versions of RSpec before 2.0 I could pipe the color output to less or redirect it to a file. In order to do it I simply have to set the RSPEC_COLOR environment variable to true. However, in the new main version of the framework this variable has stopped to define the output type (color or monchrome). Is there any way to pipe or redirect the color in RSpec 2.0 and higher?
Thanks.
Debian GNU/Linux 5.0.7;
Ruby 1.9.2;
RSpec 2.4.0.
Updated
I found the answer by myself.
One should use the tty configuration option to achieve the effect.
Here's the example:
# spec/spec_helper.rb
RSpec.configure do |config|
config.tty = true
end
The answer in the question is the correct one:
# spec/spec_helper.rb
RSpec.configure do |config|
config.tty = true
end
Then rspec | grep --color="never" something keeps the coloring.
By looking at the sources, it seems that the color_enabled configuration option is now in the Configuration module of RSpec. However, if the output is not done to a tty, color is disabled.
My suggestion would be to set color_enabled = true and to monkey patch the RSpec Configuration module so that is works even when not outputting to a tty:
module RSpec
module Core
class Configuration
def color_enabled
true
end
end
end
end
This is not the nicest way, though. This is also untested and I think that monkey patching rspec is not the easiest thing to do because usually tests are run via the dedicated command line tool.
Maybe you could open a bug report to the maintainer and ask for a force_color_enabled option ? It would probably be very quick to implement...
Good Luck and Happy Coding !
It's as simple as:
# spec/spec_helper.rb
RSpec.configure do |config|
config.color_enabled = true
end

Equivalent of cURL for Ruby?

Is there a cURL library for Ruby?
Curb and Curl::Multi provide cURL bindings for Ruby.
If you like it less low-level, there is also Typhoeus, which is built on top of Curl::Multi.
Use OpenURI and
open("http://...", :http_basic_authentication=>[user, password])
accessing sites/pages/resources that require HTTP authentication.
Curb-fu is a wrapper around Curb which in turn uses libcurl. What does Curb-fu offer over Curb? Just a lot of syntactic sugar - but that can be often what you need.
HTTP clients is a good page to help you make decisions about the various clients.
You might also have a look at Rest-Client
If you know how to write your request as a curl command, there is an online tool that can turn it into ruby (2.0+) code: curl-to-ruby
Currently, it knows the following options: -d/--data, -H/--header, -I/--head, -u/--user, --url, and -X/--request. It is open to contributions.
the eat gem is a "replacement" for OpenURI, so you need to install the gem eat in the first place
$ gem install eat
Now you can use it
require 'eat'
eat('http://yahoo.com') #=> String
eat('/home/seamus/foo.txt') #=> String
eat('file:///home/seamus/foo.txt') #=> String
It uses HTTPClient under the hood. It also has some options:
eat('http://yahoo.com', :timeout => 10) # timeout after 10 seconds
eat('http://yahoo.com', :limit => 1024) # only read the first 1024 chars
eat('https://yahoo.com', :openssl_verify_mode => 'none') # don't bother verifying SSL certificate
Here's a little program I wrote to get some files with.
base = "http://media.pragprog.com/titles/ruby3/code/samples/tutthreads_"
for i in 1..50
url = "#{ base }#{ i }.rb"
file = "tutthreads_#{i}.rb"
File.open(file, 'w') do |f|
system "curl -o #{f.path} #{url}"
end
end
I know it could be a little more eloquent but it serves it purpose. Check it out. I just cobbled it together today because I got tired of going to each URL to get the code for the book that was not included in the source download.
There's also Mechanize, which is a very high-level web scraping client that uses Nokogiri for HTML parsing.
Adding a more recent answer, HTTPClient is another Ruby library that uses libcurl, supports parallel threads and lots of the curl goodies. I use HTTPClient and Typhoeus for any non-trivial apps.
To state the maybe-too-obvious, tick marks execute shell code in Ruby as well. Provided your Ruby code is running in a shell that has curl:
puts `curl http://www.google.com?q=hello`
or
result = `
curl -X POST https://www.myurl.com/users \
-d "name=pat" \
-d "age=21"
`
puts result
A nice minimal reproducible example to copy/paste into your rails console:
require 'open-uri'
require 'nokogiri'
url = "https://www.example.com"
html_file = URI.open(url)
doc = Nokogiri::HTML(html_file)
doc.css("h1").text
# => "Example Domain"

How do you run a specific test with test/spec (not a specific file, but a spec within a given file)?

With Test::Unit, I can run:
ruby path/to/test.rb --name=test_name_that_i_want_to_run
Thus far, I have not been able to figure out how to do this with test/spec specifications. I am wondering if the way that specifications are automatically named does not allow me to do something like this.
Take the following spec for example:
require 'rubygems'
require 'spec'
describe 'tests' do
it 'should be true' do
1.should == 1
end
it 'should be false' do
1.should_not == 2
end
end
You can execute a single spec by using the -e flag and providing the portion specified by the it block. e.g. ruby my_spec.rb -e 'should be false'
After contacting the gem maintainer, Christian Neukirchen, I found out how to do this, so I am documenting it here for future reference.
specrb path/to/test.rb --name ".*should behave this way.*"
I needed to use the specrb test runner, an extended version Test::Unit's test runner, rather than just the ruby command.
You can also do this with the ruby command:
ruby path/to/test.rb -n "/should behave this way/"

Resources