Skip to content
Josh Cheek edited this page Jan 8, 2017 · 1 revision

These things have been useful for integrating.

If you want to execute from some specific directory (e.g. if your editor is in the wrong directory) try using Dir.chdir at the top of the script. E.g. I used that here so I could run with a full Rails app, see the section titled "Completely against the real env".

If you want some specific file to be available in that environment, require the fullpath to the file. Eg I used that here to load up the Rails schema in the section titled "Running against the real schema".

You can set the $LOAD_PATH to a gem you're working on and then require files as if it was installed.

You can work with gets by setting $stdin to the DATA segment and writing inputs there.

$stdin = DATA

puts "What's your name?"
name = gets.chomp
puts "What's your favourite colour?"
colour = gets.chomp
puts "#{name}'s favourite colour is #{colour}."

# >> What's your name?
# >> What's your favourite colour?
# >> Josh's favourite colour is brown.

__END__
Josh
brown

If you're trying to show an error vs a non-error, you can rescue the lines you expect to explode so that it displays the expected error and continues evaluating.

lambda { |x| x }.call()     rescue $!  # => #<ArgumentError: wrong number of arguments (given 0, expected 1)>
lambda { |x| x }.call(1)               # => 1
lambda { |x| x }.call(1, 2) rescue $!  # => #<ArgumentError: wrong number of arguments (given 2, expected 1)>

On Unix, fork is useful for looking at what a program does when run two different ways.

class A
  fork && raise("omg")  # => nil
rescue
  $!                    # => #<RuntimeError: omg>
else
  :nothing_raised       # => :nothing_raised
end                     # => #<RuntimeError: omg>, :nothing_raised