Ruby unable to use require - ruby

This is a newbie question as I am attempting to learn Ruby by myself, so apologies if it sounds like a silly question!
I am reading through the examples of why's (poignant) guide to ruby and am in chapter 4. I typed the code_words Hash into a file called wordlist.rb
I opened another file and typed the first line as require 'wordlist.rb' and the rest of the code as below
#Get evil idea and swap in code
print "Enter your ideas "
idea = gets
code_words.each do |real, code|
idea.gsub!(real, code)
end
#Save the gibberish to a new file
print "File encoded, please enter a name to save the file"
ideas_name = gets.strip
File::open( 'idea-' + ideas_name + '.txt', 'w' ) do |f|
f << idea
end
When I execute this code, it fails with the following error message:
C:/MyCode/MyRubyCode/filecoder.rb:5: undefined local variable or method `code_words' for main:Object (NameError)
I use Windows XP and Ruby version ruby 1.8.6
I know I should be setting something like a ClassPath, but not sure where/how to do so!
Many thanks in advance!

While the top-level of all files are executed in the same context, each file has its own script context for local variables. In other words, each file has its own set of local variables that can be accessed throughout that file, but not in other files.
On the other hand, constants (CodeWords), globals ($code_words) and methods (def code_words) would be accessible across files.
Some solutions:
CodeWords = {:real => "code"}
$code_words = {:real => "code"}
def code_words
{:real => "code"}
end
An OO solution that is definitely too complex for this case:
# first file
class CodeWords
DEFAULT = {:real => "code"}
attr_reader :words
def initialize(words = nil)
#words = words || DEFAULT
end
end
# second file
print "Enter your ideas "
idea = gets
code_words = CodeWords.new
code_words.words.each do |real, code|
idea.gsub!(real, code)
end
#Save the gibberish to a new file
print "File encoded, please enter a name to save the file"
ideas_name = gets.strip
File::open( 'idea-' + ideas_name + '.txt', 'w' ) do |f|
f << idea
end

I think the problem might be that the require executes the code in another context, so the runtime variable is no longer available after the require.
What you could try is making it a constant:
CodeWords = { :real => 'code' }
That will be available everywhere.
Here is some background on variable scopes etc.

I was just looking at the same example and was having the same problem.
What I did was change the variable name in both files from code_words to $code_words .
This would make it a global variable and thus accesible by both files right?
My question is: wouldn't this be a simpler solution than making it a constant and having to write CodeWords = { :real => 'code' } or is there a reason not to do it ?

A simpler way would be to use the Marshal.dump feature to save the code words.
# Save to File
code_words = {
'starmonkeys' => 'Phil and Pete, those prickly chancellors of the New Reich',
'catapult' => 'chucky go-go', 'firebomb' => 'Heat-Assisted Living',
'Nigeria' => "Ny and Jerry's Dry Cleaning (with Donuts)",
'Put the kabosh on' => 'Put the cable box on'
}
# Serialize
f = File.open('codewords','w')
Marshal.dump(code_words, f)
f.close
Now at the beginning of your file you would put this:
# Load the Serialized Data
code_words = Marshal.load(File.open('codewords','r'))

Here's the easy way to make sure you can always include a file that's in the same directory as your app, put this before the require statement
$:.unshift File.dirname(__FILE__)
$: is the global variable representing the "CLASSPATH"

Related

Debugging in rails Console

I have this script that i would like to test within the rails console
Gem.find_files("models/*.rb").each do |f|
filename = File.basename(f, '.*')
class_name_symbol = filename.classify.to_sym
autoload class_name_symbol, "models/#{filename}"
end
what i would like to do is print out the results in the console but can only get as far as outputting the array using
Gem.find_files("models/*.rb")
which returns this
["/home/richardlewis/.rvm/gems/ruby-1.9.3-p448#myblogView/bundler/gems/blogModels-8360dfc861ad/lib/models/portfolio_sector.rb", "/home/richardlewis/.rvm/gems/ruby-1.9.3-p448#myblogView/bundler/gems/blogModels-8360dfc861ad/lib/models/post.rb", "/home/richardlewis/.rvm/gems/ruby-1.9.3-p448#myblogView/bundler/gems/blogModels-8360dfc861ad/lib/models/image.rb", "/home/richardlewis/.rvm/gems/ruby-1.9.3-p448#myblogView/bundler/gems/blogModels-8360dfc861ad/lib/models/message.rb", "/home/richardlewis/.rvm/gems/ruby-1.9.3-p448#myblogView/bundler/gems/blogModels-8360dfc861ad/lib/models/sector.rb", "/home/richardlewis/.rvm/gems/ruby-1.9.3-p448#myblogView/bundler/gems/blogModels-8360dfc861ad/lib/models/portfolio.rb", "/home/richardlewis/.rvm/gems/ruby-1.9.3-p448#myblogView/bundler/gems/blogModels-8360dfc861ad/lib/models/category.rb"]
tips appreciated
After using answer the output is
models/portfolio_sector
models/post
models/message
models/sector
models/portfolio
models/category
=> ["/home/richardlewis/.rvm/gems/ruby-1.9.3-p448#myblogView/bundler/gems/blogModels-8360dfc861ad/lib/models/portfolio_sector.rb", "/home/richardlewis/.rvm/gems/ruby-1.9.3-p448#myblogView/bundler/gems/blogModels-8360dfc861ad/lib/models/post.rb", "/home/richardlewis/.rvm/gems/ruby-1.9.3-p448#myblogView/bundler/gems/blogModels-8360dfc861ad/lib/models/image.rb", "/home/richardlewis/.rvm/gems/ruby-1.9.3-p448#myblogView/bundler/gems/blogModels-8360dfc861ad/lib/models/message.rb", "/home/richardlewis/.rvm/gems/ruby-1.9.3-p448#myblogView/bundler/gems/blogModels-8360dfc861ad/lib/models/sector.rb", "/home/richardlewis/.rvm/gems/ruby-1.9.3-p448#myblogView/bundler/gems/blogModels-8360dfc861ad/lib/models/portfolio.rb", "/home/richardlewis/.rvm/gems/ruby-1.9.3-p448#myblogView/bundler/gems/blogModels-8360dfc861ad/lib/models/category.rb"]
not sure why the array is at the end?
Edit :
The script is supposed to take each item in the array and autoload the file contained in models/#{filename}. I would like to print out all the model/#{filename} paths in the console to ensure they are correct –
Gem.find_files("models/*.rb").each do |f|
filename = File.basename(f, '.*')
# So, instead of passing this filename to autoload, you print it. Or do both.
puts "models/#{filename}"
# class_name_symbol = filename.classify.to_sym
# autoload class_name_symbol, "models/#{filename}"
end && nil # suppress return value from `each`

Retrieve a file in Ruby

So what I am trying to do is pass a file name into a method and and check if the file is closed. What I am struggling to do is getting a file object from the file name without actually opening the file.
def file_is_closed(file_name)
file = # The method I am looking for
file.closed?
end
I have to fill in the commented part. I tried using the load_file method from the YAML module but I think that gives the content of the file instead of the actual file.
I couldn't find a method in the File module to call. Is there a method maybe that I don't know?
File#closed? returns whether that particular File object is closed, so there is no method that is going to make your current attempted solution work:
f1 = File.new("test.file")
f2 = File.new("test.file")
f1.close
f1.closed? # => true # Even though f2 still has the same file open
It would be best to retain the File object that you're using in order to ask it if it is closed, if possible.
If you really want to know if your current Ruby process has any File objects open for a particular path, something like this feels hack-ish but should mostly work:
def file_is_closed?(file_name)
ObjectSpace.each_object(File) do |f|
if File.absolute_path(f) == File.absolute_path(file_name) && !f.closed?
return false
end
end
true
end
I don't stand by that handling corner cases well, but it seems to work for me in general:
f1 = File.new("test.file")
f2 = File.new("test.file")
file_is_closed?("test.file") # => false
f1.close
file_is_closed?("test.file") # => false
f2.close
file_is_closed?("test.file") # => true
If you want to know if any process has the file open, I think you'll need to resort to something external like lsof.
For those cases where you no longer have access to the original file objects in Ruby (after fork + exec, for instance), a list of open file descriptors is available in /proc/pid/fd. Each file there is named for the file descriptor number, and is a symlink to the opened file, pipe, or socket:
# Returns hash in form fd => filename
def open_file_descriptors
Hash[
Dir.glob( File.join( '/proc', Process.pid.to_s, 'fd', '*' ) ).
map { |fn| [File.basename(fn).to_i, File.readlink(fn)] rescue [nil, nil] }.
delete_if { |fd, fn| fd.nil? or fd < 3 }
]
end
# Return IO object for the named file, or nil if it's not open
def io_for_path(path)
fd, fn = open_file_descriptors.find {|k,v| path === v}
fd.nil? ? nil : IO.for_fd(fd)
end
# close an open file
file = io_for_path('/my/open/file')
file.close unless file.nil?
The open_file_descriptors method parses the fd directory and returns a hash like {3 => '/my/open/file'}. It is then a simple matter to get the file descriptor number for the desired file, and have Ruby produce an IO object for it with for_fd.
This assumes you are on Linux, of course.

Get directory of file that instantiated a class ruby

I have a gem that has code like this inside:
def read(file)
#file = File.new file, "r"
end
Now the problem is, say you have a directory structure like so:
app/main.rb
app/templates/example.txt
and main.rb has the following code:
require 'mygem'
example = MyGem.read('templates/example.txt')
It comes up with File Not Found: templates/example.txt. It would work if example.txt was in the same directory as main.rb but not if it's in a directory. To solve this problem I've added an optional argument called relative_to in read(). This takes an absolute path so the above could would need to be:
require 'mygem'
example = MyGem.read('templates/example.txt', File.dirname(__FILE__))
That works fine, but I think it's a bit ugly. Is there anyway to make it so the class knows what file read() is being called in and works out the path based on that?
There is an interesting library - i told you it was private. One can protect their methods with it from being called from outside. The code finds the caller method's file and removes it. The offender is found using this line:
offender = caller[0].split(':')[0]
I guess you can use it in your MyGem.read code:
def read( file )
fpath = Pathname.new(file)
if fpath.relative?
offender = caller[0].split(':')[0]
fpath = File.join( File.dirname( offender ), file )
end
#file = File.new( fpath, "r" )
end
This way you can use paths, relative to your Mygem caller and not pwd. Exactly the way you tried in your app/main.rb
Well, you can use caller, and a lot more reliably than what the other people said too.
In your gem file, outside of any class or module, put this:
c = caller
req_file = nil
c.each do |s|
if(s =~ /(require|require_relative)/)
req_file = File.dirname(File.expand_path(s.split(':')[0])) #Does not work for filepaths with colons!
break
end
end
REQUIRING_FILE_PATH = req_file
This will work 90% of the time, unless the requiring script executed a Dir.chdir. The File.expand_path depends on that. I'm afraid that unless your requirer passes their __FILE__, there's nothing you can do if they change the working dir.
Also you may check for caller:
def read(file)
if /^(?<file>.+?):.*?/ =~ caller(1).first
caller_dir, caller_file = Pathname.new(Regexp.last_match[:file]).split
file_with_path = File.join caller_dir, file
#file = File.new "#{file_with_path}", "r"
end
end
I would not suggest you to do so (the code above will break being called indirectly, because of caller(1), see reference to documentation on caller). Furthermore, the regex above should be tuned more accurately if the caller path is intended to contain colons.
This should work for typical uses (I'm not sure how resistant it is to indirect use, as mentioned by madusobwa above):
def read_relative(file)
#file = File.new File.join(File.dirname(caller.first), file)
end
On a side note, consider adding a block form of your method that closes the file after yielding. In the current form you're forcing clients to wrap their use of your gem with an ensure.
Accept a file path String as an argument. Convert to a Pathname object. Check if the path is relative. If yes, then convert to absolute.
def read(file)
fpath = Pathname.new(file)
if fpath.relative?
fpath = File.expand_path(File.join(File.dirname(__FILE__),file))
end
#file = File.new(fpath,"r")
end
You can make this code more succinct (less verbose).

how to find the file path from the open command

I need to get the path of the file in fo variable so that i can pass the path to the unzip_file function. how do i get the path here?
url = 'http://www.dtniq.com/product/mktsymbols_v2.zip'
open(url, 'r') do |fo|
puts "unzipfile "
unzip_file(fo, "c:\\temp11\\")
end
In terms of how to do it I would do this:
Find out the class of the object I am dealing with
ruby-1.9.2-p290 :001 > tmp_file = open('tmp.txt', 'r')
=> #<File:tmp.txt>
ruby-1.9.2-p290 :001 > tmp_file.class
=> File
Go look up the documentation for that class
Google Search : ruby file
Which returns Class: File ruby-doc.org => www.ruby-doc.org/core/classes/File.html
Look at the methods. There is one called path -> looks interesting
If I haven't found an answer by now then
Continue looking around google/stack overflow for a bit
I really can't find a solution that matches my problem. Time to ask a question on here
Most of the time 1..3 should get you what you need. Once you learn to read the documentation you can do things a lot quicker. It's just trying to overcome how difficult it is to get into the docs when you first start.
The fo in your block should be a Tempfile so you can use the path method:
url = 'http://www.dtniq.com/product/mktsymbols_v2.zip'
open(url, 'r') do |fo|
puts "unzipfile "
unzip_file(fo.path, "c:\\temp11\\")
end

Find and replace in a file in Ruby

I have this little program I write in ruby. I found a nice piece of code here, on SO, to find and replace something in a file, but it doesn't seems to work.
Here's the code:
#!/usr/bin/env ruby
DOC = "test.txt"
FIND = /,,^M/
SEP = "\n"
#make substitution
File.read(DOC).gsub(FIND, SEP)
#Check if the line already exist
unique_lines = File.readlines(DOC).uniq
#Save the result in a new file
File.open('test2.txt', 'w') { |f| f.puts(unique_lines) }
Thanks everybody !
I skip the check you make to see if the line already exists and usually go with something like this (here I want to replace 'FOO' with 'BAR'):
full_path_to_read = File.expand_path('~/test1.txt')
full_path_to_write = File.expand_path('~/test2.txt')
File.open(full_path_to_read) do |source_file|
contents = source_file.read
contents.gsub!(/FOO/, 'BAR')
File.open(full_path_to_write, "w+") { |f| f.write(contents) }
end
The use of expand_path is also probably a bit pedantic here, but I like it just so that I don't accidentally clobber some file I didn't mean to.

Resources