-
-
Notifications
You must be signed in to change notification settings - Fork 383
/
rails.vim
5101 lines (4689 loc) · 170 KB
/
rails.vim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
" autoload/rails.vim
" Author: Tim Pope <http://tpo.pe/>
" Install this file as autoload/rails.vim.
if exists('g:autoloaded_rails') || &cp
finish
endif
let g:autoloaded_rails = '5.4'
" Utility Functions {{{1
let s:app_prototype = {}
let s:file_prototype = {}
let s:buffer_prototype = {}
let s:readable_prototype = {}
function! s:add_methods(namespace, method_names)
for name in a:method_names
let s:{a:namespace}_prototype[name] = s:function('s:'.a:namespace.'_'.name)
endfor
endfunction
function! s:function(name) abort
return function(substitute(a:name, '^s:', matchstr(expand('<sfile>'), '.*\zs<SNR>\d\+_'), ''))
endfunction
function! s:sub(str,pat,rep)
return substitute(a:str,'\v\C'.a:pat,a:rep,'')
endfunction
function! s:gsub(str,pat,rep)
return substitute(a:str,'\v\C'.a:pat,a:rep,'g')
endfunction
function! s:startswith(string,prefix)
return strpart(a:string, 0, strlen(a:prefix)) ==# a:prefix
endfunction
function! s:endswith(string,suffix)
return strpart(a:string, len(a:string) - len(a:suffix), len(a:suffix)) ==# a:suffix
endfunction
function! s:uniq(list) abort
let i = 0
let seen = {}
while i < len(a:list)
let key = string(a:list[i])
if has_key(seen, key)
call remove(a:list, i)
else
let seen[key] = 1
let i += 1
endif
endwhile
return a:list
endfunction
function! s:getlist(arg, key)
let value = get(a:arg, a:key, [])
return type(value) == type([]) ? copy(value) : [value]
endfunction
function! s:split(arg, ...)
return type(a:arg) == type([]) ? copy(a:arg) : split(a:arg, a:0 ? a:1 : "\n")
endfunction
function! rails#lencmp(i1, i2) abort
return len(a:i1) - len(a:i2)
endfunction
function! s:escarg(p)
return s:gsub(a:p,'[ !%#]','\\&')
endfunction
function! s:esccmd(p)
return s:gsub(a:p,'[!%#]','\\&')
endfunction
function! s:rquote(str)
if a:str =~ '^[A-Za-z0-9_/.:-]\+$'
return a:str
elseif &shell =~? 'cmd'
return '"'.s:gsub(s:gsub(a:str, '"', '""'), '\%', '"%"').'"'
else
return shellescape(a:str)
endif
endfunction
function! s:fnameescape(file) abort
if exists('*fnameescape')
return fnameescape(a:file)
else
return escape(a:file," \t\n*?[{`$\\%#'\"|!<")
endif
endfunction
function! s:dot_relative(path) abort
let slash = matchstr(a:path, '^\%(\w\:\)\=\zs[\/]')
if !empty(slash)
let path = fnamemodify(a:path, ':.')
if path !=# a:path
return '.' . slash . path
endif
endif
return a:path
endfunction
function! s:mods(mods) abort
return s:gsub(a:mods, '[<]mods[>]\s*|^\s', '')
endfunction
function! s:webcat() abort
if !exists('s:webcat')
if executable('curl')
let s:webcat = 'curl'
elseif executable('wget')
let s:webcat = 'wget -qO-'
else
let s:webcat = ''
endif
endif
return s:webcat
endfunction
function! s:active() abort
return !empty(get(b:, 'rails_root'))
endfunction
function! s:fcall(fn, path, ...) abort
let ns = matchstr(a:path, '^\a\a\+\ze:')
if len(ns) && exists('*' . ns . '#' . a:fn)
return call(ns . '#' . a:fn, [a:path] + a:000)
else
return call(a:fn, [a:path] + a:000)
endif
endfunction
function! s:filereadable(path) abort
return s:fcall('filereadable', a:path)
endfunction
function! s:isdirectory(path) abort
return s:fcall('isdirectory', a:path)
endfunction
function! s:getftime(path) abort
return s:fcall('getftime', a:path)
endfunction
function! s:simplify(path) abort
return s:fcall('simplify', a:path)
endfunction
function! s:glob(path) abort
if v:version >= 704
return s:fcall('glob', a:path, 0, 1)
else
return split(s:fcall('glob', a:path), "\n")
endif
endfunction
function! s:mkdir_p(path) abort
if a:path !~# '^\a\a\+:' && !isdirectory(a:path)
call mkdir(a:path, 'p')
endif
endfunction
function! s:readfile(path, ...) abort
if !s:filereadable(a:path)
return []
elseif a:0
return s:fcall('readfile', a:path, '', a:1)
else
return s:fcall('readfile', a:path)
endif
endfunction
function! s:readbuf(path,...) abort
let nr = bufnr('^'.a:path.'$')
if nr < 0 && exists('+shellslash') && ! &shellslash
let nr = bufnr('^'.s:gsub(a:path,'/','\\').'$')
endif
if bufloaded(nr)
return getbufline(nr,1,a:0 ? a:1 : '$')
elseif a:0
return s:readfile(a:path, a:1)
else
return s:readfile(a:path)
endif
endfunction
function! s:pop_command()
if exists("s:command_stack") && len(s:command_stack) > 0
exe remove(s:command_stack,-1)
endif
endfunction
function! s:push_chdir(...)
if !exists("s:command_stack") | let s:command_stack = [] | endif
if s:active() && (a:0 ? getcwd() !=# rails#app().path() : !s:startswith(getcwd(), rails#app().real()))
let chdir = exists("*haslocaldir") && haslocaldir() ? "lchdir " : "chdir "
call add(s:command_stack,chdir.s:escarg(getcwd()))
exe chdir.s:escarg(rails#app().real())
else
call add(s:command_stack,"")
endif
endfunction
function! s:app_real(...) dict abort
let pre = substitute(matchstr(self._root, '^\a\a\+\ze:'), '^.', '\u&', '')
if empty(pre)
let real = self._root
elseif exists('*' . pre . 'Real')
let real = {pre}Real(self._root)
else
return ''
endif
return join([real]+a:000,'/')
endfunction
function! s:app_path(...) dict dict
if a:0 && a:1 =~# '\%(^\|^\w*:\)[\/]'
return a:1
else
return join([self._root]+a:000,'/')
endif
endfunction
function! s:app_spec(...) dict abort
if a:0 && a:1 =~# '\%(^\|^\w*:\)[\/]'
return a:1
else
return join([self._root]+a:000,'/')
endif
endfunction
function! s:app_root(...) dict abort
if a:0 && a:1 =~# '\%(^\|^\w*:\)[\/]'
return a:1
else
return join([self._root]+a:000,'/')
endif
endfunction
function! s:app_has_path(path) dict abort
return s:getftime(self.path(a:path)) != -1
endfunction
function! s:app_has_file(file) dict abort
let file = self.path(a:file)
return a:file =~# '/$' ? s:isdirectory(file) : s:filereadable(file)
endfunction
function! s:find_file(name, ...) abort
let args = copy(a:000)
let path = s:pathsplit(len(args) ? remove(args, 0) : &path)
let suffixes = s:pathsplit(len(args) ? remove(args, 0) : [])
let default = ''
if type(get(args, 0)) == type('')
let default = remove(args, 0)
endif
let index = get(args, 0, 1)
let results = []
for glob in path
for dir in s:glob(glob)
let dir = substitute(substitute(dir, '[\/]\=$', '/', ''), '^+\ze\a\a\+:', '', '')
for suf in [''] + (a:name =~# '/$' ? [] : suffixes)
if s:fcall(a:name =~# '/$' ? 'isdirectory' : 'filereadable', dir . a:name . suf)
call add(results, dir . a:name . suf)
endif
if len(results) == index
return results[-1]
endif
endfor
endfor
endfor
return index == -1 ? results : default
endfunction
function! s:app_find_file(name, ...) dict abort
if a:0
let path = map(s:pathsplit(a:1),'self.path(v:val)')
else
let path = [self.path()]
endif
return call('s:find_file', [a:name, path] + a:000[1:-1])
endfunction
call s:add_methods('app',['real','path','spec','root','has_path','has_file','find_file'])
" Split a path into a list.
function! s:pathsplit(path) abort
if type(a:path) == type([]) | return copy(a:path) | endif
return split(s:gsub(a:path, '\\ ', ' '), ',')
endfunction
" Convert a list to a path.
function! s:pathjoin(...) abort
let i = 0
let path = ""
while i < a:0
if type(a:000[i]) == type([])
let path .= "," . escape(join(a:000[i], ','), ' ')
else
let path .= "," . a:000[i]
endif
let i += 1
endwhile
return substitute(path,'^,','','')
endfunction
function! s:readable_end_of(lnum) dict abort
if a:lnum == 0
return 0
endif
let cline = self.getline(a:lnum)
let spc = matchstr(cline,'^\s*')
let endpat = '\<end\>'
if matchstr(self.getline(a:lnum+1),'^'.spc) && !matchstr(self.getline(a:lnum+1),'^'.spc.endpat) && matchstr(cline,endpat)
return a:lnum
endif
let endl = a:lnum
while endl <= self.line_count()
let endl += 1
if self.getline(endl) =~ '^'.spc.endpat
return endl
elseif self.getline(endl) =~ '^=begin\>'
while self.getline(endl) !~ '^=end\>' && endl <= self.line_count()
let endl += 1
endwhile
let endl += 1
elseif self.getline(endl) !~ '^'.spc && self.getline(endl) !~ '^\s*\%(#.*\)\=$'
return 0
endif
endwhile
return 0
endfunction
function! s:endof(lnum)
return rails#buffer().end_of(a:lnum)
endfunction
function! s:readable_last_opening_line(start,pattern,limit) dict abort
let line = a:start
while line > a:limit && self.getline(line) !~ a:pattern
let line -= 1
endwhile
if self.name() =~# '\.\%(rb\|rake\)$'
let lend = self.end_of(line)
else
let lend = -1
endif
if line > a:limit && (lend < 0 || lend >= a:start)
return line
else
return -1
endif
endfunction
function! s:lastopeningline(pattern,limit,start)
return rails#buffer().last_opening_line(a:start,a:pattern,a:limit)
endfunction
let s:sql_define = substitute(
\ '\v\c^\s*create %(or replace )=%(table|%(materialized |recursive )=view|%(unique |fulltext )=index|trigger|function|procedure|sequence|extension) %(if not exists )=%(\i+\.)=[`"]=',
\ ' ', '\\s+', 'g')
function! s:readable_define_pattern() dict abort
if self.name() =~# '\.yml\%(\.example\|sample\)\=$'
return '^\%(\h\k*:\)\@='
elseif self.name() =~# '\.sql$'
return s:sql_define
endif
let define = '^\s*def\s\+\(self\.\)\='
if self.name() =~# '\.rake$'
let define .= "\\\|^\\s*\\%(task\\\|file\\)\\s\\+[:'\"]"
endif
if self.name() =~# '/schema\.rb$'
let define .= "\\\|^\\s*create_table\\s\\+[:'\"]"
endif
if self.name() =~# '\.erb$'
let define .= '\|\<id=["'']\='
endif
if self.name() =~# '\.haml$'
let define .= '\|^\s*\%(%\w*\)\=\%(\.[[:alnum:]_-]\+\)*#'
endif
if self.type_name('test')
let define .= '\|^\s*test\s*[''"]'
endif
return define
endfunction
function! s:readable_last_method_line(start) dict abort
return self.last_opening_line(a:start,self.define_pattern(),0)
endfunction
function! s:lastmethodline(start)
return rails#buffer().last_method_line(a:start)
endfunction
function! s:readable_last_method(start) dict abort
let lnum = self.last_method_line(a:start)
let line = self.getline(lnum)
if line =~# '^\s*test\s*\([''"]\).*\1'
let string = matchstr(line,'^\s*\w\+\s*\([''"]\)\zs.*\ze\1')
return 'test_'.s:gsub(string,' +','_')
elseif lnum
return s:sub(matchstr(line,'\%('.self.define_pattern().'\m\)\zs\h\%(\k\|[:.]\)*[?!=]\='),':$','')
else
return ""
endif
endfunction
function! s:lastmethod(...)
return rails#buffer().last_method(a:0 ? a:1 : line("."))
endfunction
function! s:readable_format(start) dict abort
if a:start
let format = matchstr(self.getline(a:start), '\%(:formats *=>\|\<formats:\) *\[\= *[:''"]\zs\w\+')
if format !=# ''
return format
endif
endif
if self.type_name('view')
let format = fnamemodify(self.path(),':r:e')
if empty(format)
return get({'rhtml': 'html', 'rxml': 'xml', 'rjs': 'js', 'haml': 'html'},
\ matchstr(self.path(),'\.\zs\w\+$'), '')
else
return format
endif
endif
if !a:start
return ''
endif
let rline = self.last_opening_line(a:start,'\C^\s*\%(mail\>.*\|respond_to\)\s*\%(\<do\|{\)\s*|\zs\h\k*\ze|',self.last_method_line(a:start))
if rline
let variable = matchstr(self.getline(rline),'\C^\s*\%(mail\>.*\|respond_to\)\s*\%(\<do\|{\)\s*|\zs\h\k*\ze|')
let line = a:start
while line > rline
let match = matchstr(self.getline(line),'\C^\s*'.variable.'\s*\.\s*\zs\h\k*')
if match != ''
return match
endif
let line -= 1
endwhile
endif
return self.type_name('mailer') ? 'text' : 'html'
endfunction
function! s:format()
return rails#buffer().format(line('.'))
endfunction
call s:add_methods('readable',['end_of','last_opening_line','last_method_line','last_method','format','define_pattern'])
function! s:readable_find_affinity() dict abort
let f = self.name()
let all = self.app().projections()
for pattern in reverse(sort(filter(keys(all), 'v:val =~# "^[^*{}]*\\*[^*{}]*$"'), s:function('rails#lencmp')))
if !has_key(all[pattern], 'affinity')
continue
endif
let [prefix, suffix; _] = split(pattern, '\*', 1)
if s:startswith(f, prefix) && s:endswith(f, suffix)
let root = f[strlen(prefix) : -strlen(suffix)-1]
return [all[pattern].affinity, root]
endif
endfor
return ['', '']
endfunction
function! s:controller(...)
return rails#buffer().controller_name(a:0 ? a:1 : 0)
endfunction
function! s:readable_controller_name(...) dict abort
let f = self.name()
if has_key(self,'getvar') && !empty(self.getvar('rails_controller'))
return self.getvar('rails_controller')
endif
let [affinity, root] = self.find_affinity()
if affinity ==# 'controller'
return root
elseif affinity ==# 'resource'
return rails#pluralize(root)
endif
if f =~# '^app/views/layouts/'
return s:sub(f,'^app/views/layouts/(.{-})\..*','\1')
elseif f =~# '^app/views/'
return s:sub(f,'^app/views/(.{-})/\w+%(\.[[:alnum:]_+]+)=\.\w+$','\1')
elseif f =~# '^app/helpers/.*_helper\.rb$'
return s:sub(f,'^app/helpers/(.{-})_helper\.rb$','\1')
elseif f =~# '^app/controllers/.*\.rb$'
return s:sub(f,'^app/controllers/(.{-})%(_controller)=\.rb$','\1')
elseif f =~# '^app/mailers/.*\.rb$'
return s:sub(f,'^app/mailers/(.{-})\.rb$','\1')
elseif f =~# '^\%(test\|spec\)/mailers/previews/.*_preview\.rb$'
return s:sub(f,'^%(test|spec)/mailers/previews/(.{-})_preview\.rb$','\1')
elseif f =~# '^app/jobs/.*\.rb$'
return s:sub(f,'^app/jobs/(.{-})%(_job)=\.rb$','\1')
elseif f =~# '^test/\%(functional\|controllers\)/.*_test\.rb$'
return s:sub(f,'^test/%(functional|controllers)/(.{-})%(_controller)=_test\.rb$','\1')
elseif f =~# '^test/\%(unit/\)\?helpers/.*_helper_test\.rb$'
return s:sub(f,'^test/%(unit/)?helpers/(.{-})_helper_test\.rb$','\1')
elseif f =~# '^spec/controllers/.*_spec\.rb$'
return s:sub(f,'^spec/controllers/(.{-})%(_controller)=_spec\.rb$','\1')
elseif f =~# '^spec/jobs/.*_spec\.rb$'
return s:sub(f,'^spec/jobs/(.{-})%(_job)=_spec\.rb$','\1')
elseif f =~# '^spec/helpers/.*_helper_spec\.rb$'
return s:sub(f,'^spec/helpers/(.{-})_helper_spec\.rb$','\1')
elseif f =~# '^spec/views/.*/\w\+_view_spec\.rb$'
return s:sub(f,'^spec/views/(.{-})/\w+_view_spec\.rb$','\1')
elseif f =~# '^app/models/.*\.rb$' && self.type_name('mailer')
return s:sub(f,'^app/models/(.{-})\.rb$','\1')
elseif f =~# '^\%(public\|app/assets\)/stylesheets/[^.]\+\.'
return s:sub(f,'^%(public|app/assets)/stylesheets/(.{-})\..*$','\1')
elseif f =~# '^\%(public\|app/assets\)/javascripts/.[^.]\+\.'
return s:sub(f,'^%(public|app/assets)/javascripts/(.{-})\..*$','\1')
elseif a:0 && a:1
return rails#pluralize(self.model_name())
endif
return ""
endfunction
function! s:model(...)
return rails#buffer().model_name(a:0 ? a:1 : 0)
endfunction
function! s:readable_model_name(...) dict abort
let f = self.name()
if has_key(self,'getvar') && !empty(self.getvar('rails_model'))
return self.getvar('rails_model')
endif
let [affinity, root] = self.find_affinity()
if affinity ==# 'model'
return root
elseif affinity ==# 'collection'
return rails#singularize(root)
endif
if f =~# '^app/models/.*_observer.rb$'
return s:sub(f,'^app/models/(.*)_observer\.rb$','\1')
elseif f =~# '^app/models/.*\.rb$'
return s:sub(f,'^app/models/(.*)\.rb$','\1')
elseif f =~# '^test/\%(unit\|models\)/.*_observer_test\.rb$'
return s:sub(f,'^test/unit/(.*)_observer_test\.rb$','\1')
elseif f =~# '^test/\%(unit\|models\)/.*_test\.rb$'
return s:sub(f,'^test/%(unit|models)/(.*)_test\.rb$','\1')
elseif f =~# '^spec/models/.*_spec\.rb$'
return s:sub(f,'^spec/models/(.*)_spec\.rb$','\1')
elseif f =~# '^\%(test\|spec\)/blueprints/.*\.rb$'
return s:sub(f,'^%(test|spec)/blueprints/(.{-})%(_blueprint)=\.rb$','\1')
elseif f =~# '^\%(test\|spec\)/exemplars/.*_exemplar\.rb$'
return s:sub(f,'^%(test|spec)/exemplars/(.*)_exemplar\.rb$','\1')
elseif f =~# '^\%(test/\|spec/\)\=factories/.*_factory\.rb$'
return s:sub(f,'^%(test/|spec/)=factories/(.{-})_factory.rb$','\1')
elseif f =~# '^\%(test/\|spec/\)\=fabricators/.*\.rb$'
return s:sub(f,'^%(test/|spec/)=fabricators/(.{-})_fabricator.rb$','\1')
elseif f =~# '^\%(test\|spec\)/\%(fixtures\|factories\|fabricators\)/.*\.\w\+$'
return rails#singularize(s:sub(f,'^%(test|spec)/\w+/(.*)\.\w+$','\1'))
elseif a:0 && a:1
return rails#singularize(s:sub(self.controller_name(), '_mailer$', ''))
endif
return ""
endfunction
call s:add_methods('readable', ['find_affinity', 'controller_name', 'model_name'])
function! s:file_lines() dict abort
let ftime = s:getftime(self.path())
if ftime > get(self,'last_lines_ftime',0)
let self.last_lines = s:readfile(self.path())
let self.last_lines_ftime = ftime
endif
return get(self,'last_lines',[])
endfunction
function! s:file_getline(lnum,...) dict abort
if a:0
return self.lines()[a:lnum-1 : a:1-1]
else
return self.lines()[a:lnum-1]
endif
endfunction
function! s:buffer_lines() dict abort
return self.getline(1,'$')
endfunction
function! s:buffer_getline(...) dict abort
if a:0 == 1
return get(call('getbufline',[self.number()]+a:000),0,'')
else
return call('getbufline',[self.number()]+a:000)
endif
endfunction
function! s:readable_line_count() dict abort
return len(self.lines())
endfunction
function! s:environment()
if exists('$RAILS_ENV')
return $RAILS_ENV
elseif exists('$RACK_ENV')
return $RACK_ENV
else
return "development"
endif
endfunction
function! s:Complete_environments(...) abort
return s:completion_filter(rails#app().environments(),a:0 ? a:1 : "")
endfunction
function! s:warn(str) abort
echohl WarningMsg
echomsg a:str
echohl None
" Sometimes required to flush output
echo ""
let v:warningmsg = a:str
return ''
endfunction
function! s:error(str) abort
echohl ErrorMsg
echomsg a:str
echohl None
let v:errmsg = a:str
return ''
endfunction
function! s:debug(str)
if exists("g:rails_debug") && g:rails_debug
echohl Debug
echomsg a:str
echohl None
endif
endfunction
function! s:buffer_getvar(varname) dict abort
return getbufvar(self.number(),a:varname)
endfunction
function! s:buffer_setvar(varname, val) dict abort
return setbufvar(self.number(),a:varname,a:val)
endfunction
call s:add_methods('buffer',['getvar','setvar'])
" }}}1
" Public Interface {{{1
function! rails#underscore(str, ...) abort
let str = s:gsub(a:str,'::','/')
let str = s:gsub(str,'(\u+)(\u\l)','\1_\2')
let str = s:gsub(str,'(\l|\d)(\u)','\1_\2')
let str = tolower(str)
return a:0 && a:1 ? s:sub(str, '^/', '') : str
endfunction
function! rails#camelize(str) abort
let str = s:gsub(a:str,'/(.=)','::\u\1')
let str = s:gsub(str,'%([_-]|<)(.)','\u\1')
return str
endfunction
function! rails#singularize(word) abort
" Probably not worth it to be as comprehensive as Rails but we can
" still hit the common cases.
let word = a:word
if word =~? '\.js$\|redis$' || empty(word)
return word
endif
let word = s:sub(word,'eople$','ersons')
let word = s:sub(word,'%([Mm]ov|[aeio])@<!ies$','ys')
let word = s:sub(word,'xe[ns]$','xs')
let word = s:sub(word,'ves$','fs')
let word = s:sub(word,'ss%(es)=$','sss')
let word = s:sub(word,'s$','')
let word = s:sub(word,'%([nrt]ch|tatus|lias)\zse$','')
let word = s:sub(word,'%(nd|rt)\zsice$','ex')
return word
endfunction
function! rails#pluralize(word, ...) abort
let word = a:word
if empty(word)
return word
endif
if a:0 && a:1 && word !=# rails#singularize(word)
return word
endif
let word = s:sub(word,'[aeio]@<!y$','ie')
let word = s:sub(word,'%(nd|rt)@<=ex$','ice')
let word = s:sub(word,'%([sxz]|[cs]h)$','&e')
let word = s:sub(word,'f@<!f$','ve')
let word .= 's'
let word = s:sub(word,'ersons$','eople')
return word
endfunction
function! rails#app(...) abort
let root = s:sub(a:0 && len(a:1) ? a:1 : get(b:, 'rails_root', ''), '[\/]$', '')
if !empty(root)
if !has_key(s:apps, root)
let s:apps[root] = deepcopy(s:app_prototype)
let s:apps[root]._root = root
endif
return get(s:apps, root, {})
endif
return {}
endfunction
function! rails#buffer(...)
return extend(extend({'#': bufnr(a:0 ? a:1 : '%')},s:buffer_prototype,'keep'),s:readable_prototype,'keep')
endfunction
function! s:buffer_app() dict abort
if len(self.getvar('rails_root'))
return rails#app(self.getvar('rails_root'))
else
throw 'Not in a Rails app'
endif
endfunction
function! s:readable_app() dict abort
return self._app
endfunction
function! rails#revision() abort
return 1000*matchstr(g:autoloaded_rails,'^\d\+')+matchstr(g:autoloaded_rails,'[1-9]\d*$')
endfunction
function! s:app_file(name) dict abort
return extend(extend({'_app': self, '_name': a:name}, s:file_prototype,'keep'),s:readable_prototype,'keep')
endfunction
function! s:readable_relative() dict abort
return self.name()
endfunction
function! s:readable_absolute() dict abort
return self.path()
endfunction
function! s:readable_spec() dict abort
return self.path()
endfunction
function! s:file_path() dict abort
return self.app().path(self._name)
endfunction
function! s:file_name() dict abort
return self._name
endfunction
function! s:buffer_number() dict abort
return self['#']
endfunction
function! s:buffer_path() dict abort
let bufname = bufname(self.number())
return empty(bufname) ? '' : s:gsub(fnamemodify(bufname,':p'),'\\ @!','/')
endfunction
function! s:buffer_name() dict abort
let app = self.app()
let bufname = bufname(self.number())
let f = len(bufname) ? fnamemodify(bufname, ':p') : ''
if f !~# ':[\/][\/]'
let f = resolve(f)
endif
let f = s:gsub(f, '\\ @!', '/')
let f = s:sub(f,'/$','')
let sep = matchstr(f,'^[^\\/:]\+\zs[\\/]')
if len(sep)
let f = getcwd().sep.f
endif
if s:startswith(tolower(f),s:gsub(tolower(app.path()),'\\ @!','/')) || f == ""
return strpart(f,strlen(app.path())+1)
else
if !exists("s:path_warn") && &verbose
let s:path_warn = 1
call s:warn("File ".f." does not appear to be under the Rails root ".self.app().path().". Please report to the rails.vim author!")
endif
return f
endif
endfunction
function! s:readable_calculate_file_type() dict abort
let f = self.name()
let e = matchstr(f, '\.\zs[^.\/]\+$')
let ae = e
if ae ==# 'erb'
let ae = matchstr(f, '\.\zs[^.\/]\+\ze\.erb$')
endif
let r = "-"
let full_path = self.path()
if empty(f)
let r = ""
elseif f =~# '^app/controllers/concerns/.*\.rb$'
let r = "controller-concern"
elseif f =~# '_controller\.rb$' || f =~# '^app/controllers/.*\.rb$'
let r = "controller"
elseif f =~# '^test/test_helper\.rb$'
let r = "test"
elseif f =~# '^spec/\%(spec\|rails\)_helper\.rb$'
let r = "spec"
elseif f =~# '_helper\.rb$'
let r = "helper"
elseif f =~# '^app/mailers/.*\.rb'
let r = "mailer"
elseif f =~# '^\%(test\|spec\)/mailers/previews/.*_preview\.rb'
let r = "mailerpreview"
elseif f =~# '^app/jobs/.*\.rb'
let r = "job"
elseif f =~# '^app/models/concerns/.*\.rb$'
let r = "model-concern"
elseif f =~# '^app/models/'
let top = "\n".join(s:readbuf(full_path,50),"\n")
let class = matchstr(top,"\n".'\s*class\s\+\S\+\s*<\s*\<\zs\S\+\>')
let type = tolower(matchstr(class, '^Application\zs[A-Z]\w*$\|^Acti\w\w\zs[A-Z]\w*\ze::Base'))
if type ==# 'mailer' || f =~# '_mailer\.rb$'
let r = 'mailer'
elseif class ==# 'ActiveRecord::Observer'
let r = 'model-observer'
elseif !empty(type)
let r = 'model-'.type
elseif top =~# '\n\s*\%(self\.\%(table_name\|primary_key\)\|has_one\|has_many\|belongs_to\)\>'
let r = 'model-record'
else
let r = 'model'
endif
elseif f =~# '^app/views/.*/_\w\+\%(\.[[:alnum:]_+]\+\)\=\.\w\+$'
let r = "view-partial-" . e
elseif f =~# '^app/views/layouts\>.*\.'
let r = "view-layout-" . e
elseif f =~# '^app/views\>.*\.'
let r = "view-" . e
elseif f =~# '^test/unit/.*_helper\.rb$'
let r = "test-helper"
elseif f =~# '^test/unit/.*\.rb$'
let r = "test-model"
elseif f =~# '^test/functional/.*_controller_test\.rb$'
let r = "test-controller"
elseif f =~# '^test/integration/.*_test\.rb$'
let r = "test-integration"
elseif f =~# '^test/lib/.*_test\.rb$'
let r = "test-lib"
elseif f =~# '^test/\w*s/.*_test\.rb$'
let r = s:sub(f,'.*<test/(\w*)s/.*','test-\1')
elseif f =~# '^test/.*_test\.rb'
let r = "test"
elseif f =~# '^spec/lib/.*_spec\.rb$'
let r = 'spec-lib'
elseif f =~# '^lib/.*\.rb$'
let r = 'lib'
elseif f =~# '^spec/\w*s/.*_spec\.rb$'
let r = s:sub(f,'.*<spec/(\w*)s/.*','spec-\1')
elseif f =~# '^features/.*\.feature$'
let r = 'cucumber-feature'
elseif f =~# '^features/step_definitions/.*_steps\.rb$'
let r = 'cucumber-steps'
elseif f =~# '^features/.*\.rb$'
let r = 'cucumber'
elseif f =~# '^spec/.*\.feature$'
let r = 'spec-feature'
elseif f =~# '^\%(test\|spec\)/fixtures\>'
if e ==# "yml"
let r = "fixtures-yaml"
else
let r = "fixtures" . (empty(e) ? "" : "-" . e)
endif
elseif f =~# '^\%(test\|spec\)/\%(factories\|fabricators\)\>'
let r = "fixtures-replacement"
elseif f =~# '^spec/.*_spec\.rb'
let r = "spec"
elseif f =~# '^spec/support/.*\.rb'
let r = "spec"
elseif f =~# '^db/migrate\>'
let r = "db-migration"
elseif f=~# '^db/schema\.rb$'
let r = "db-schema"
elseif f =~# '\.rake$' || f =~# '^\%(Rake\|Cap\)file$' || f =~# '^config/deploy\.rb$' || f =~# '^config/deploy/.*\.rb$'
let r = "task"
elseif f =~# '^log/.*\.log$'
let r = "log"
elseif ae ==# "css" || ae =~# "^s[ac]ss$" || ae ==# "^less$"
let r = "stylesheet-".ae
elseif ae ==# "js" || ae ==# "es6"
let r = "javascript"
elseif ae ==# "coffee"
let r = "javascript-coffee"
elseif e ==# "html"
let r = e
elseif f =~# '^config/routes\>.*\.rb$'
let r = "config-routes"
elseif f =~# '^config/'
let r = "config"
endif
return r
endfunction
function! s:buffer_type_name(...) dict abort
let type = getbufvar(self.number(),'rails_cached_file_type')
if empty(type)
let type = self.calculate_file_type()
endif
return call('s:match_type',[type ==# '-' ? '' : type] + a:000)
endfunction
function! s:readable_type_name(...) dict abort
let type = self.calculate_file_type()
return call('s:match_type',[type ==# '-' ? '' : type] + a:000)
endfunction
function! s:match_type(type,...)
if a:0
return !empty(filter(copy(a:000),'a:type =~# "^".v:val."\\%(-\\|$\\)"'))
else
return a:type
endif
endfunction
function! s:app_environments() dict
if self.cache.needs('environments')
call self.cache.set('environments',self.relglob('config/environments/','**/*','.rb'))
endif
return copy(self.cache.get('environments'))
endfunction
function! s:app_default_locale() dict abort
if self.cache.needs('default_locale')
let candidates = map(filter(
\ s:readfile(self.path('config/application.rb')) + s:readfile(self.path('config/environment.rb')),
\ 'v:val =~# "^ *config.i18n.default_locale = :[\"'']\\=[A-Za-z-]\\+[\"'']\\= *$"'
\ ), 'matchstr(v:val,"[A-Za-z-]\\+\\ze[\"'']\\= *$")')
call self.cache.set('default_locale', get(candidates, 0, 'en'))
endif
return self.cache.get('default_locale')
endfunction
function! s:app_stylesheet_suffix() dict abort
if self.cache.needs('stylesheet_suffix')
let default = self.has_gem('sass-rails') ? '.scss' : '.css'
let candidates = map(filter(
\ s:readfile(self.path('config/application.rb')),
\ 'v:val =~# "^ *config.sass.preferred_syntax *= *:[A-Za-z-]\\+ *$"'
\ ), '".".matchstr(v:val,"[A-Za-z-]\\+\\ze *$")')
call self.cache.set('stylesheet_suffix', get(candidates, 0, default))
endif
return self.cache.get('stylesheet_suffix')
endfunction
function! s:app_has(feature) dict
let map = {
\'test': 'test/',
\'spec': 'spec/',
\'bundler': 'Gemfile|gems.locked',
\'rails2': 'script/about',
\'rails3': 'config/application.rb',
\'rails5': 'app/assets/config/manifest.js|config/initializers/application_controller_renderer.rb',
\'cucumber': 'features/',
\'webpack': 'app/javascript/packs/',
\'turnip': 'spec/acceptance/',
\'sass': 'public/stylesheets/sass/'}
if self.cache.needs('features')
call self.cache.set('features',{})
endif
let features = self.cache.get('features')
if !has_key(features,a:feature)
let path = get(map,a:feature,a:feature.'/')
let features[a:feature] =
\ !empty(filter(split(path, '|'), 'self.has_file(v:val)'))
endif
return features[a:feature]
endfunction
function! s:app_has_rails5() abort dict
let gemdir = get(self.gems(), 'railties')
return self.has('rails5') || gemdir =~# '-\%([5-9]\|\d\d\+\)\.[^\/]*$'
endfunction
call s:add_methods('app',['default_locale','environments','file','has','has_rails5','stylesheet_suffix'])
call s:add_methods('file',['path','name','lines','getline'])
call s:add_methods('buffer',['app','number','path','name','lines','getline','type_name'])
call s:add_methods('readable',['app','relative','absolute','spec','calculate_file_type','type_name','line_count'])
" }}}1
" Ruby Execution {{{1
function! s:app_has_zeus() dict abort
return getftype(self.real('zeus.sock')) ==# 'socket' && executable('zeus')
endfunction
function! s:app_ruby_script_command(cmd) dict abort