Copy paste from irb excluding prompt at start of line? - ruby

When copy/pasting from irb to an .rb file the start of each line should be removed.
A short example, say you copy this from irb:
irb(main):049:1* def thing(x, y)
irb(main):050:1* out = x * y
irb(main):051:1* puts out
irb(main):052:0> end
=> :thing
irb(main):053:0> thing(2, 3)
6
=> nil
it would be handy to paste only this:
def thing(x, y)
out = x * y
puts out
end
=> :thing
thing(2, 3)
6
=> nil
Is there any special copy/paste command to achieve this, either already built into irb, available through some sort of extension, or even operating system shortcut (running macOS)?
What I tried
A regular expression could be used to remove the prompts, but it's not ideal since it assumes the paste will be into a text editor with find and replace with regex.
Although completely unrelated to rails, Google Docs, has a convention of cmd + shift + paste to 'paste without formatting'. I'm after something similar for irb like 'copy without prompt'.
Note: I'm using the macOS terminal (zsh)

You can hold the ⌥ Option key and drag for a rectangular selection:
You can also customize IRB's prompt. Here's an example of the built-in --noprompt option which provides a blank prompt:

Related

Open Editor From Command Line and Fetch Input

I'm currently working on a feature for CocoaPods, a Ruby gem. There's an existing command that accepts a number of options. I'd like to add an extra option that enables the user to enter a custom message by opening the default text editor and, when the user saves and quits the editor, the message is fed to the command that was executed.
What I want to replicate is how you can add -m to the git commit command to have you enter a commit message. I have little experience with creating command line tools so any help is much appreciated.
The goal is to execute a specific command command --message, open the editor, have the user enter a custom message, and execute the command with the custom message being one of the arguments stored in argv.
The common workflow is:
the caller application creates a temporary file;
determines the default editor (for Debian-based it would be /usr/bin/editor, for other linuces — the content of shell variable $EDITOR, etc);
runs a shell command in a subshell with Kernel#system (not with backticks!);
waits for it to exit;
determines the exit code, and skips following if it is not 0;
reads the content of temporary file, created in step 1 and removes this file.
In ruby that would be like:
▶ f = Tempfile.new 'cocoapods'
#⇒ #<File:/tmp/am/cocoapods20151120-6901-u2lubx>
-rw------- 1 am am 0 nov 20 15:03 /tmp/am/cocoapods20151120-6901-u2lubx
▶ path = f.path
#⇒ "/tmp/am/cocoapods20151120-6901-u2lubx"
▶ f.puts 'This content is already presented in file'
#⇒ nil
▶ f.close # HERE MUST BE ENSURE BLOCK, BUT FOR THE SAKE OF AN EXAMPLE...
#⇒ nil
▶ system "editor #{path}"
#⇒ Vim: Warning: Output is not to a terminal
If you are testing this in console, just type anything, followed by Esc:wq. In real life there will be normal vim (or what the default editor is) opened.
▶ File.read path
#⇒ "GGGGGGGGGThis content is already presented in file\n"
All together:
#!/usr/bin/env ruby
require 'tempfile'
f = Tempfile.new 'cocoapods'
path = f.path
f.puts 'This content is already presented in file'
f.close # HERE MUST BE ENSURE BLOCK, BUT FOR THE SAKE OF AN EXAMPLE...
system "editor #{path}"
puts File.read path

Ruby saying file doesnt exist

I'm new to Ruby, and I am writing a test program just to get some of the features down. Here is the program
#!/usr/bin/env ruby
class FileManager
def read_file(filename)
return nil unless File.exist?(filename)
File.read(filename)
end
end
if __FILE__ == $0
fm = FileManager.new
puts "What file would you like to open?"
fname = gets
puts fm.read_file fname
end
As you can see, it is very simple. If I comment the first line of the read_file method, I get this error
No such file or directory - /Users/macuser/Projects/Aptana\ Studio\ 3\ Workspace/Ruby\ Test/text (Errno::ENOENT)
from /Users/macuser/Projects/Aptana Studio 3 Workspace/Ruby Test/ruby.rb:6:in `read_file'
from /Users/macuser/Projects/Aptana Studio 3 Workspace/Ruby Test/ruby.rb:15:in `<main>'
when I run the program and use this file: /Users/macuser/Projects/Aptana\ Studio\ 3\ Workspace/Ruby\ Test/text
However, if I run cat /Users/macuser/Projects/Aptana\ Studio\ 3\ Workspace/Ruby\ Test/text, it outputs Hello, world!, as it should.
I don't believe it's a permissions issue because I own the folder, but just in case I've tried running the program as root. Also, I have made sure that fname is the actual name of the file, not nil. I've tried both escaped and unescaped versions of the path, along with just text or the full path. I know for a fact the file exists, so why is Ruby giving me this error?
With gets filename the filename includes a newline \n.
You have to remove it in your filename:
gets filename
p filename #"test.rb\n"
p File.exist?(filename) #false
p File.exist?(filename.chomp) #true
(And you don't need to mask the spaces)
It looks like you're shell-escaping your spaces even though gets does not go through a shell. You want to enter "/Users/macuser/Projects/Aptana Studio 3 Workspace/Ruby Test/text" instead of "/Users/macuser/Projects/Aptana\ Studio\ 3\ Workspace/Ruby\ Test/text".

Change Bash terminal output color while running a Ruby script

I'd like to briefly change my terminal output color, run a Ruby script so that standard output prints in that changed color, 'sleep' for a second, and then change it back. I know how to set colors, like for the prompt:
PS1="\e[0;36m[\w] \e[m "
I imagine I need to write a Bash function to do this. What would that look like?
Here is a Ruby script to show all the terminal colors. Download it or run the code below.
def color(index)
normal = "\e[#{index}m#{index}\e[0m"
bold = "\e[#{index}m\e[1m#{index}\e[0m"
"#{normal} #{bold} "
end
8.times do|index|
line = color(index + 1)
line += color(index + 30)
line += color(index + 90)
line += color(index + 40)
line += color(index + 100)
puts line
end
You can do it within Ruby (assuming you're on Linux; Windows requires a library/gem whose name I can't remember at the moment) using the normal codes you would use in bash, e.g.
puts "\e[31m etc Your text here."
To reset to normal display:
puts "\e[0m"
Adjust to taste.
You can also use the Term Ansicolor gem to change it from inside a running script.
http://flori.github.io/term-ansicolor/
One may also use the Colorize gem.
Installation:
sudo gem install colorize
Usage:
require 'colorize'
puts "I am now red.".red
puts "I am now blue.".green
puts "I am a super coder".yellow
This answer is copied from How can I use Ruby to colorize the text output to a terminal?.

How do I get the output of an Xcode user script to auto indent?

The Problem
I want to press a key when I have a line highlighted and convert from a single line:
JGLogEntry *logEntry = [JGLogEntry applicationNoWindowsFrom:date1 to:date2 intoMOC:mockRawMOC];
to a multiline statement:
JGLogEntry *logEntry = [JGLogEntry applicationNoWindowsFrom:date1
to:date2
intoMOC:mockRawMOC];
What I've Tried
I've got a simple ruby script that almost gets me there.
#!/usr/bin/env ruby
s = STDIN.read
s.gsub!(/(:.+?\w) (\w.+?)/,'\1' + "\n\t" +'\2')
print s
When I set the output to "Replace Selection", I get this:
JGLogEntry *logEntry = [JGLogEntry applicationNoWindowsFrom:date1
to:date2
intoMOC:mockRawMOC];
When I set the output to "Place on Clipboard", then paste it in, I get the desired result:
JGLogEntry *logEntry = [JGLogEntry applicationNoWindowsFrom:date1
to:date2
intoMOC:mockRawMOC];
However, this is two keypresses which is clumsy.
Any ideas how I can get the replaced text to obey Xcode's auto indent rules?
Check the pre-installed script for "Convert tabs to spaces", and how it executes an in-line applescript. Use that to tell XCode to perform the menu item
Edit > Format > Re-Indent
I'm not sure how you do that with ruby, nor the details about the applescript content, but I would wager it's fairly straight-forward..

How to enable ruby methods visualizing in vim

a have googled the question, but found nothing - maybe I do not know how to define the search keywords properly in this case.
I like to use folding in vim when I'm developing Ruby on Rails applications. And my foldcolumn is set to 4. But its visualizing of the start and the end of the ruby method is not so simple and obvious ("-" - "def", "|" - "end"):
-def foo
bar = 1
|end
The question is - is there any plugin for vim, that will show markers (arrows or stmh) near every "def" and "end" like it is done in TextMate (1)?
v def foo
bar = 1
^ end
Also, as I do not have much experience in vim/ruby, maybe there is another, more elegant way to check that all def-end pairs are closed in a particular file? (matchit.vim is not very comfortable for this need)
I hope there is more convenient way to catch lost "ends" than to read "Syntax error" in the console :)
I'm not sure whether it's quite what you need, but have you tried the 'foldcolumn' option? For example, with:
:set foldcolumn=4
You'll get something like this:
- def foo
| bar = 1
| end
- def foo2
| bar = 2
|- if x == 1
|| bar = 3
|| end
| end
See :help 'foldcolumn' for more information. Note that you can click on the - signs to close the folds if your Vim is mouse-enabled.
Edit
If you don't like the fold method, you could use signs (assuming your Vim is signs enabled). Try something like this:
command! RubySigns call RubySigns()
" Optional:
au BufReadPost *.rb call RubySigns()
function! RubySigns()
sign define ruby_end text=^
sign define ruby_def text=v
sign unplace *
g/^\s*\(def\|class\|begin\)\>/exe 'sign place '.line('.').' line='.line('.').' name=ruby_def buffer='.bufnr('%')
g/^\s*end\>/exe 'sign place '.line('.').' line='.line('.').' name=ruby_end buffer='.bufnr('%')
endfunction
It's probably not perfect (I don't know ruby), but it might give you something to get started.

Resources