Character set issues in filepath using ruby on XP - ruby-on-rails

I'm trying to do a File.exist?(file) but my ruby script doesn't find the file because of \, spaces, - and . in the filepath. I'm a beginner in ruby and need some help to fix this.

I assume it has to do with your OS, more then with Ruby.
file tèst.rb:
puts "Hello"
puts "smørebrød"
used in irb:
irb(main):001:0> require "tèst.rb"
Hello
smørebrød
Ruby can include a file with name tèst.rb just fine.
irb(main):005:0> f = File.new("ÅÄÖ.txt")
irb(main):006:0> f.each {|l| p l }
"\"Hej Verden\"\n"
loading a file with your requested characters and printing its lines (p l) works just fine.
I am running ruby 1.8.7 on Ubuntu Linux. That is a rather old Ruby.

Related

Bulk validating yaml files

I need to validate a whole bunch of YAML files.
I tried the yaml online parser (http://yaml-online-parser.appspot.com/) which works perfect, but it's too much manual work to copy each YAML file content into the box and parse them.
Is there a way to parse/validate YAML files in bulk?
This is fairly straightforward in any scripting language that has a YAML library. For example, here's how you might do it in Ruby:
#!/usr/bin/env ruby
require "yaml"
def check_file(filename)
YAML.parse_file(filename)
puts "OK"
0
rescue Psych::SyntaxError => ex
puts "Error#{ex.message[/: .+/]}"
1
end
exit_code = 0
max_filename_length = ARGV.max_by(&:size).size
ARGV.each do |filename|
printf "%-*s ", max_filename_length, filename
exit_code |= check_file(filename)
end
exit exit_code
Usage:
$ ruby check_yaml.rb *.yml
config-1.yml OK
config-2.yml OK
invalid.yml Error: did not find expected key while parsing a block mapping at line 2 column 3
xyzzy.yml OK
$ echo $EXIT_CODE
1
Just want to share another YAML parser that I found useful too.
https://www.npmjs.com/package/yaml-to-json
Thank you all for helping with this!

How to execute 5 different ruby files in series

I'm new to ruby and I'm trying to run 5 different files in a folder. I'd like to execute them all in series mean one after another.
the list of my files are:
Scripts/aaa. rb
Scripts/bbb. rb
Scripts/ccc. rb
Scripts/ddd. rb
Scripts/eee. rb
My script should run the aaa.rb first and then rest
Do as below using Dir::chdir, Dir::glob:
Dir.chdir("path/to/the/.rb files") do |path|
Dir.glob("*.rb").sort.each do |name|
system("ruby #{name}")
end
end
create another ruby script to run them in order
["aaa", "bbb", "ccc", "ddd", "eee"].each do |name|
system("ruby #{name}.rb") #give the full path of the file here
end
Depending on your OS, you can use a batch file, or a shell script. In either case, that's exactly their purpose. Assuming you have the executable bit set on the files:
On *nix or Mac OS:
#!/bin/sh
Scripts/aaa.rb
Scripts/bbb.rb
Scripts/ccc.rb
Scripts/ddd.rb
Scripts/eee.rb
as a simplistic script.
For something a bit more "DRY":
#!/bin/sh
pushdir Scripts
for i in aaa bbb ccc ddd eee
do
$i.rb
done
popdir
If the executable-bit isn't set, precede the name of the file with the path to your Ruby executable, something like:
/usr/local/bin/ruby Scripts/aaa.rb
There are a lot of other ways to point to the Ruby executable, so your mileage might vary.

rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/psych.rb:205:in `parse': (<unknown>): could not find expected ':' while scanning a simple key at line 18 column 3

This is the full error I am getting when doing a simple:
$ rails generate
Users/localuser/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/psych.rb:205:in
`parse': (): could not find expected ':' while scanning a
simple key at line 18 column 3(Psych::SyntaxError)
Any ideas whats going on?
My system:
ruby 2.0.0p0 [x86_64-darwin12.2.0] Rails 3.2.13 mysql Ver 14.14
Distrib 5.6.10, for osx10.8 (x86_64)
This an extract of the psych.rb file mentioned in the error
#See Psych::Nodes for more information about YAML AST.
def self.parse_stream yaml, filename = nil, &block
if block_given?
parser = Psych::Parser.new(Handlers::DocumentStream.new(&block))
parser.parse yaml, filename
else
parser = self.parser
parser.parse yaml, filename
parser.handler.root
end
end
This error usually appears if you have a syntax error in your YAML file(s).
I had this error when I had a tab instead of whitespace in the yaml file.
I had this error when the YAML ended in a NULL '\0' character instead of empty whitespace.

Running two different interpreters on same script

I have a script written in Ironruby that uses a C# .dll to retrieve a hash. I then use that hash throughout the rest of my Ruby code. I would rather not run my entire script off of the Ironruby interpreter. Is there anyway to run a section of code on the IR interpreter, get the hash, and execute the rest of the code via the regular Ruby interpreter?
Thanks
One possible solution is to split up the script into two parts,
the first part executed by iron ruby has to save his state in a yaml file before handing control to the second part which will run by ruby
here a small demo:
C:\devkit\home\demo>demo
"running program:demo_ir.rb"
"the first part of the script running by the iron_ruby interpreter"
"my_hash attributes:"
"attr1: first value"
"attr2: second value"
"attr3: 2012"
"hash_store_filename:temp.yaml"
"running program:demo_ruby.rb"
"hash_store_filename:temp.yaml"
"the second part of the script running by ruby 1.8.x interpreter"
"my_hash attributes:"
"attr1: first value"
"attr2: second value"
"attr3: 2012"
here the source of the first part for ironruby (demo_ir.rb):
require "yaml"
p "running program:#{$0}"
hash_store_filename = ARGV[0]
my_hash = { attr1: 'first value', attr2: 'second value', attr3: 2012}
p "the first part of the script running by the iron_ruby interpreter"
p "my_hash attributes:"
p "attr1: #{my_hash[:attr1]}"
p "attr2: #{my_hash[:attr2]}"
p "attr3: #{my_hash[:attr3]}"
# save the state of the script in an array where my_hash is the first element
p "hash_store_filename:#{hash_store_filename}"
File.open( hash_store_filename, 'w' ) do |out|
YAML.dump( [my_hash], out )
end
here the code of the second part for ruby 1.8 (demo_ruby.rb)
require "yaml"
p "running program:#{$0}"
hash_store_filename = ARGV[0]
p "hash_store_filename:#{hash_store_filename}"
ar = YAML.load_file(hash_store_filename)
my_hash=ar[0]
p "the second part of the script running by ruby 1.8.x interpreter"
p "my_hash attributes:"
p "attr1: #{my_hash[:attr1]}"
p "attr2: #{my_hash[:attr2]}"
p "attr3: #{my_hash[:attr3]}"
and the launcher:
#ECHO OFF
REM file: demo.bat
SET TEMP_YAML=temp.yaml
ir demo_ir.rb %TEMP_YAML%
ruby demo_ruby.rb %TEMP_YAML%
del %TEMP_YAML%
if you run the script in a concurrent environment you can generate a unique temporary name of the yaml file in the ironruby script avoiding that two process ( or thread ) try to write the same file.
If you prefer you could use some C# line of code, instead of a .bat, to integrate the two parts of the script, but this is a is a bit more difficult (IMHO)
I successfully test this solution using:
C:\devkit\home\demo>ir -v
IronRuby 1.1.3.0 on .NET 4.0.30319.239
C:\devkit\home\demo>ruby -v
ruby 1.8.7 (2011-12-28 patchlevel 357) [i386-mingw32]
ask if you need some clarification

rails - Redirecting console output to a file

On a bash console, if I do this:
cd mydir
ls -l > mydir.txt
The > operator captures the standard input and redirects it to a file; so I get the listing of files in mydir.txt instead of in the standard output.
Is there any way to do something similar on the rails console?
I've got a ruby statement that generates lots of prints (~8k lines) and I'd like to be able to see it completely, but the console only "remembers" the last 1024 lines or so. So I thought about redirecting to a file - If anyone knows a better option, I'm all ears.
A quick one-off solution:
irb:001> f = File.new('statements.xml', 'w')
irb:002> f << Account.find(1).statements.to_xml
irb:003> f.close
Create a JSON fixture:
irb:004> f = File.new(Rails.root + 'spec/fixtures/qbo/amy_cust.json', 'w')
irb:005> f << JSON.pretty_generate((q.get :customer, 1).as_json)
irb:006> f.close
You can use override $stdout to redirect the console output:
$stdout = File.new('console.out', 'w')
You may also need to call this once:
$stdout.sync = true
To restore:
$stdout = STDOUT
Apart from Veger's answer, there is one of more way to do it which also provides many other additional options.
Just open your rails project directory and enter the command:
rails c | tee output.txt
tee command also has many other options which you can check out by:
man tee
If you write the following code in your environment file, it should work.
if "irb" == $0
config.logger = Logger.new(Rails.root.join('path_to_log_file.txt'))
end
You can also rotate the log file using
config.logger = Logger.new(Rails.root.join('path_to_log_file.txt'), number_of_files, file_roation_size_threshold)
For logging only active record related operations, you can do
ActiveRecord::Base.logger = Logger.new(Rails.root.join('path_to_log_file.txt'))
This also lets you have different logger config/file for different environments.
Using Hirb, you can choose to log only the Hirb output to a text file.
That makes you able to still see the commands you type in into the console window, and just the model output will go to the file.
From the Hirb readme:
Although views by default are printed to STDOUT, they can be easily modified to write anywhere:
# Setup views to write to file 'console.log'.
>> Hirb::View.render_method = lambda {|output| File.open("console.log", 'w') {|f| f.write(output) } }
# Doesn't write to file because Symbol doesn't have a view and thus defaults to irb's echo mode.
>> :blah
=> :blah
# Go back to printing Hirb views to STDOUT.
>> Hirb::View.reset_render_method
Use hirb. It automatically pages any output in irb that is longer than a screenful. Put this in a console session to see this work:
>> require 'rubygems'
>> require 'hirb'
>> Hirb.enable
For more on how this works, read this post.
Try using script utility if you are on Unix-based OS.
script -c "rails runner -e development lib/scripts/my_script.rb" report.txt
That helped me capture a Rails runner script's very-very long output easily to a file.
I tried using redirecting to a file but it got written only at the end of script.
That didn't helped me because I had few interactive commands in my script.
Then I used just script and then ran the rails runner in script session but it didn't wrote everything. Then I found this script -c "runner command here" output_file and it saved all the output as was desired. This was on Ubuntu 14.04 LTS
References:
https://askubuntu.com/questions/290322/how-to-get-and-copy-a-too-long-output-completely-in-terminal#comment1668695_715798
Writing Ruby Console Output to Text File

Resources