GzipReader each_line method missing in Rubinius - ruby

I am trying to read a gzipped file using Zlib:GzipReader. This works as expected using ruby 1.9.3 but I am getting a method_missing error for each_line when using Rubinius.
Is there any way to read a gzipped file using Rubinius?
require 'zlib'
Zlib::GzipReader.open("lines.txt.gz").each_line { |line|
puts "#{line}"
}
Kernel(Zlib::GzipReader)#each_line (method_missing) at kernel/delta/kernel.rb:81

I believe this is a bug in Rubinius, you should consider opening an issue for it with the project. However, this workaround should get you going:
require 'zlib'
require 'stringio'
file = File.read("lines.txt.gz")
lines = Zlib::GzipReader.new(StringIO.new(file)).read

Related

Do not necessary require(s) matter?

I want to be able to have one ruby file that can require all the common dependencies, so that other files can just have one require on this shared file.for example; I have foo.rb and bar.rb and allrequires.rb. I want to have the line require "allrequires.rb" in both foo.rb and bar.rb, but bar.rb doesn't need all the requires.
Does it matter if I use require in .rb file that do not really require that file? Could it have an impact on performance maybe?
I am currently on ruby 1.8.7 (2010-08-16 patchlevel 302) [i386-mingw32]
Update
It looks like it is not the best idea to 'share'/use all requires in both .rb files. What would be solution to that?
Right now I can think of using file name in a condition.
There's two main performance penalties:
The time taken to do the require itself. In Ruby 1.9.1 and Ruby 1.9.2, the time taken to do all the requires had worse than linear scalability - if you doubled the number of requires, it took you more than twice as long - I think it took you four times as long.
The time taken to execute the code in the file being required. If you have code like the following, then executing the code will take a non-trivial amount of time.
class MyClass
MY_CONSTANT = File.read("data.txt")
end
Another approach of conditional requiring, the following script gives no error on the JSON parser because it is named require1.rb, in scripts that have no name like require1.rb of script2.rb the gem isn't required
require 'json' if "require1.rb, script2.rb"[File.basename(__FILE__)]
p File.basename(__FILE__)
text = '[{ "name" : "car", "status": "good"}, { "name" : "bus", "status": "bad"},{ "name" : "taxi", "status": "soso"},
{"noname":"", "status" : "worse"}
]'
data = JSON.parse(text)
p data.collect { |item| item['name'] }
EDIT: here a version that uses an array
["require1.rb","script1.rb"].find{|script|require 'json' if script===File.basename(__FILE__)}
Yes, there will be a speedpanalty, you can benchmark how mutch to consider if it realy matters.
With multiple require's i put hem in my code like this so that it doens't take much screenspace.
['green_shoes','Hpricot'].each(&method(:require))
You could also do a conditional require, but that would be ugly having all around your code
begin
data = JSON.parse(text)
rescue
require 'json_pure'
data = JSON.parse(text)
end
So in short, give each rb its own require's
My final solution is (in case someone finds it useful):
requires.rb is called from web.rb or testweb.rb, rufus.rb or testrufus.rb
called_from=caller[0].split(":")[0]
puts "loading web 'requires' for file: #{called_from} ..." if (["web"].any?{|s| called_from[s]})
puts "loading web 'requires' for file: #{called_from} ..." if (["rufus"].any?{|s| called_from[s]})
puts "loading web 'requires' for file: #{called_from} ..." if (["settings"].any?{|s| called_from[s]})
require 'rubygems'
require 'socket' if (["web","settings"].any?{|s| called_from[s]})
require 'ruby-growl' if (["web","settings","rufus"].any?{|s| called_from[s]})
require 'sinatra' if (["web"].any?{|s| called_from[s]})
Thank you #Andrew for the explanation and #peter for the hint how to solve this.

Add Ruby Source Code as HTML to RDoc

How do I include a ruby code file, as is, into RDoc?
I have an example.rb file that documents how to use my gem and I would like to include that as one of the files like the README.rdoc and HISTORY.rdoc.
I've already figured out how to convert the ruby source code into HTML using the Syntax gem but I can't figure out how to make RDoc include the file without parsing it.
When I tell RDoc to include the html file it isn't listed and if I fake it out by using rdoc or txt as the file extension it doesn't display properly (the file is still actually html).
I've got a solution that works it's just incredibly ugly. There has got to be a better way to do this that's native to rdoc but I don't see it.
Here's what I have in my Rakefile:
# Build rdocs
require 'rake/rdoctask'
require 'syntax/convertors/html'
rdoc_dir = 'rdoc'
# This is rdoc1 but it doesn't work unless you DON'T wrap it in a task
# Generate html files from example ruby files
convertor = Syntax::Convertors::HTML.for_syntax "ruby"
replacement_key = "REPLACE_THIS_TEXT_WITH_PROPER_HTML"
# Create dummy files
Dir.glob('examples/*.rb').each do |file|
File.open("#{file}.txt", "w") do |dummy_file|
dummy_file.write(replacement_key)
end
end
# Call the rdoc task
Rake::RDocTask.new(:rdoc2) do |rdoc|
rdoc.rdoc_dir = rdoc_dir
rdoc.title = "pickled_optparse #{version}"
rdoc.rdoc_files.include('README*')
rdoc.rdoc_files.include('HISTORY*')
rdoc.rdoc_files.include('examples/*.txt')
rdoc.rdoc_files.include('lib/**/*.rb')
end
task :rdoc3 do
# Now use a hammer to replace the dummy text with the
# html we want to use in our ruby example code file.
html_header = File.read('rake_reqs/html_header.html')
Dir.glob('examples/*.rb').each do |file|
html_ruby = convertor.convert(File.read(file))
rdoc_file = "#{rdoc_dir}/examples/#{File.basename(file,".rb")}_rb_txt.html"
fixed_html = File.read(rdoc_file).gsub!(replacement_key, "#{html_header}#{html_ruby}")
File.open(rdoc_file, "w") {|f| f.write(fixed_html)}
File.delete("#{file}.txt")
end
end
task :rdoc => [:rdoc2, :rdoc3]
Sorry I can't give you an actual answer but I'm looking at sdoc myself.
You can install the gem from ruby gems.

private method `split' called for nil:NilClass (NoMethodError)

I'm trying to use domainatrix with nokogiri and am coming up with a holdup. Being relatively new to ruby, I've tried every syntax variation on the Domainatrix.parse function I can to get the a href's to parse properly. They do print during the "puts" command but when I uncomment the domainatrix code problems start:
require 'rubygems'
require 'domainatrix'
require 'anemone'
require 'open-uri'
require 'nokogiri'
doc = Nokogiri::HTML(open("http://www.cnn.com"))
doc.xpath('//a/#href').each do |node|
linkage = node.text
puts linkage
url = Domainatrix.parse(linkage)
print url.domain
print url.public_suffix
end
Anyone have any ideas on this? I think it is just a syntax issue or perhaps I cannot use the Domainatrix function where I'm using it?
It was getting snagged on some improperly formatted URLs.

Getting webpage content with Ruby -- I'm having troubles

I want to get the content off this* page. Everything I've looked up gives the solution of parsing CSS elements; but, that page has none.
Here's the only code that I found that looked like it should work:
file = File.open('http://hiscore.runescape.com/index_lite.ws?player=zezima', "r")
contents = file.read
puts contents
Error:
tracker.rb:1:in 'initialize': Invalid argument - http://hiscore.runescape.com/index_lite.ws?player=zezima (Errno::EINVAL)
from tracker.rb:1:in 'open'
from tracker.rb:1
*http://hiscore.runescape.com/index_lite.ws?player=zezima
If you try to format this as a link in the post it doesn't recognize the underscore (_) in the URL for some reason.
You really want to use open() provided by the Kernel class which can read from URIs you just need to require the OpenURI library first:
require 'open-uri'
Used like so:
require 'open-uri'
file = open('http://hiscore.runescape.com/index_lite.ws?player=zezima')
contents = file.read
puts contents
This related SO thread covers the same question:
Open an IO stream from a local file or url
The appropriate way to fetch the content of a website is through the NET::HTTP module in Ruby:
require 'uri'
require 'net/http'
url = "http://hiscore.runescape.com/index_lite.ws?player=zezima"
r = Net::HTTP.get_response(URI.parse(url).host, URI.parse(url).path)
File.open() does not support URIs.
Best wishes,
Fabian
Please use open-uri, its support both uri and local files
require 'open-uri'
contents = open('http://www.google.com') {|f| f.read }

Ruby block to string instead of executing [duplicate]

This question already has answers here:
Printing the source code of a Ruby block
(6 answers)
Closed 8 years ago.
Take this example:
write_as_string { puts 'x' }
I then want to be able to do
def write_as_string(&block)
puts block.to_s
end
When I execute this, I want the output to be:
"puts 'x'"
I want to be able to receive the block and get the actual code for the block instead of executing it.
Motivation: Creating a DSL, I want to the mock to be converted into a number of other method calls, hidden from the calling code - using existing objects and methods without monkey patching them.
Any ideas on this would be great!
Thanks
Ben
If you're on Ruby 1.9, you can use the sourcify gem. It provides Proc#to_source, which is like ParseTree's Proc#to_ruby.
When using sourcify, if you have nested procs in your source code, you might have to help it along with the :attached_to option:
## (Works in Ruby 1.8) Using ParseTree (with parse_tree_extensions)
block.to_ruby
## (Works in Ruby 1.9) Using sourcify
block.to_source
## Try this if you get Sourcify::NoMatchingProcError or Sourcify::MultipleMatchingProcsPerLineError
block.to_source :attached_to => :name_of_block_in_source_code
I posted about ParseTree and Ruby 1.9 in my company's blog.
Duplicate: Printing the source code of a Ruby block
sudo gem install ParseTree
sudo gem install ruby2ruby
then
require 'rubygems'
require 'parse_tree'
require 'parse_tree_extensions'
require 'ruby2ruby'
def block_as_string &block
block.to_ruby
end
results in
irb(main):008:0> block_as_string {puts 'x'}
=> "proc { puts(\"x\") }"
You want the ruby2ruby gem, which does this nicely. Unfortunately, to analyze a block this gem depends on ParseTree, which is unsupported in Ruby 1.9.

Resources