Skip to content

Commit

Permalink
Ruby proc shorthands
Browse files Browse the repository at this point in the history
  • Loading branch information
AndrewRadev committed Mar 1, 2015
1 parent 93ad2eb commit 5abe9aa
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 0 deletions.
21 changes: 21 additions & 0 deletions autoload/sj/ruby.vim
Expand Up @@ -297,6 +297,24 @@ function! sj#ruby#JoinWhenThen()
return 0
endfunction

function! sj#ruby#SplitProcShorthand()
let pattern = '(&:\k\+)'

if sj#SearchUnderCursor(pattern) <= 0
return 0
endif

if search('(&:\zs\k\+)', '', line('.')) <= 0
return 0
endif

let method_name = expand('<cword>')
let body = " do |i|\ni.".method_name."\nend"

call sj#ReplaceMotion('Va(', body)
return 1
endfunction

function! sj#ruby#SplitBlock()
let pattern = '\v\{(\s*\|.{-}\|)?\s*(.{-})\s*\}'

Expand Down Expand Up @@ -360,6 +378,9 @@ function! sj#ruby#JoinBlock()

let replacement = do_line.' '.body.' '.end_line

" shorthand to_proc if possible
let replacement = substitute(replacement, '\s*{ |\(\k\+\)| \1\.\(\k\+\) }$', '(\&:\2)', '')

call sj#ReplaceLines(do_line_no, end_line_no, replacement)

return 1
Expand Down
8 changes: 8 additions & 0 deletions doc/splitjoin.txt
Expand Up @@ -258,6 +258,14 @@ Blocks ~
puts b.to_s
end
<
Block &-shorthand ~
>
[1, 2, 3].map(&:to_s)
[1, 2, 3].map do |i|
i.to_s
end
<
Heredocs ~
>
string = 'something'
Expand Down
1 change: 1 addition & 0 deletions ftplugin/ruby/splitjoin.vim
Expand Up @@ -2,6 +2,7 @@ if !exists('b:splitjoin_split_callbacks')
let b:splitjoin_split_callbacks = [
\ 'sj#ruby#SplitArrayLiteral',
\ 'sj#ruby#SplitIfClause',
\ 'sj#ruby#SplitProcShorthand',
\ 'sj#ruby#SplitBlock',
\ 'sj#ruby#SplitOptions',
\ 'sj#ruby#SplitCachingConstruct',
Expand Down
5 changes: 5 additions & 0 deletions spec/plugin/perl_spec.rb
Expand Up @@ -8,6 +8,11 @@
vim.set(:shiftwidth, 2)
end

after :all do
# The perl filetype messes with iskeyword...
vim.command('set iskeyword-=:')
end

specify "suffix if-clauses" do
set_file_contents 'print "a = $a\n" if $debug;'

Expand Down
28 changes: 28 additions & 0 deletions spec/plugin/ruby_spec.rb
Expand Up @@ -611,6 +611,34 @@
EOF
end

it "optimizes particular cases to &-shorthands" do
set_file_contents <<-EOF
[1, 2, 3, 4].map(&:to_s)
EOF

vim.search 'to_s'
split

assert_file_contents <<-EOF
[1, 2, 3, 4].map do |i|
i.to_s
end
EOF

set_file_contents <<-EOF
[1, 2, 3, 4].map do |whatever|
whatever.to_s
end
EOF

vim.search 'whatever|'
join

assert_file_contents <<-EOF
[1, 2, 3, 4].map(&:to_s)
EOF
end

it "handles trailing code" do
set_file_contents <<-EOF
Bar.new { |one| two }.map(&:name)
Expand Down

0 comments on commit 5abe9aa

Please sign in to comment.