-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathprojectile-rails.el
1961 lines (1696 loc) · 82.8 KB
/
projectile-rails.el
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
;;; projectile-rails.el --- Minor mode for Rails projects based on projectile-mode
;; Copyright (C) 2013 Adam Sokolnicki
;; Author: Adam Sokolnicki <[email protected]>
;; URL: https://github.com/asok/projectile-rails
;; Version: 0.22.0
;; Keywords: rails, projectile
;; Package-Requires: ((emacs "25.1") (projectile "0.12.0") (inflections "1.1") (inf-ruby "2.2.6") (f "0.13.0") (rake "0.3.2") (dash "2.18.1"))
;; This file is NOT part of GNU Emacs.
;;; License:
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING. If not, write to the
;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
;;; Commentary:
;;
;; To start it for the rails projects:
;;
;; (projectile-rails-global-mode)
;;
;;; Code:
(eval-when-compile (require 'cl-lib))
(require 'projectile)
(require 'autoinsert)
(require 'inf-ruby)
(require 'inflections)
(require 'f)
(require 'rake)
(require 'json)
(require 'comint)
(defgroup projectile-rails nil
"Rails mode based on projectile."
:prefix "projectile-rails-"
:group 'projectile)
(defcustom projectile-rails-controller-keywords
'("logger" "polymorphic_path" "polymorphic_url" "mail" "render" "attachments"
"default" "helper" "helper_attr" "helper_method" "layout" "url_for"
"serialize" "exempt_from_layout" "filter_parameter_logging" "hide_action"
"cache_sweeper" "protect_from_forgery" "caches_page" "cache_page"
"caches_action" "expire_page" "expire_action" "rescue_from" "params"
"request" "response" "session" "flash" "head" "redirect_to" "redirect_back"
"render_to_string" "respond_with" "before_filter" "append_before_filter"
"before_action" "append_before_action"
"prepend_before_filter" "after_filter" "append_after_filter"
"prepend_after_filter" "around_filter" "append_around_filter"
"prepend_around_filter" "skip_before_filter" "skip_after_filter" "skip_filter"
"prepend_before_action" "after_action" "append_after_action"
"prepend_after_action" "around_action" "append_around_action"
"prepend_around_action" "skip_before_action" "skip_after_action" "skip_action")
"List of keywords to highlight for controllers."
:group 'projectile-rails
:type '(repeat string))
(defcustom projectile-rails-migration-keywords
'("create_table" "change_table" "drop_table" "rename_table" "add_column"
"rename_column" "change_column" "change_column_default" "change_column_null"
"remove_column" "add_index" "remove_index" "rename_index" "execute"
"add_timestamps" "remove_timestamps" "add_foreign_key" "remove_foreign_key"
"add_reference" "remove_reference" "add_belongs_to" "remove_belongs_to"
"transaction" "reversible" "revert" "announce")
"List of keywords to highlight for migrations."
:group 'projectile-rails
:type '(repeat string))
(defcustom projectile-rails-model-keywords
'("default_scope" "named_scope" "scope" "serialize" "belongs_to" "has_one"
"has_many" "has_and_belongs_to_many" "composed_of" "accepts_nested_attributes_for"
"before_create" "before_destroy" "before_save" "before_update" "before_validation"
"before_validation_on_create" "before_validation_on_update" "after_create"
"after_destroy" "after_save" "after_update" "after_validation"
"after_validation_on_create" "after_validation_on_update" "around_create"
"around_destroy" "around_save" "around_update" "after_commit" "after_find"
"after_initialize" "after_rollback" "after_touch" "attr_accessible"
"attr_protected" "attr_readonly" "validates" "validate" "validate_on_create"
"validate_on_update" "validates_acceptance_of" "validates_associated"
"validates_confirmation_of" "validates_each" "validates_exclusion_of"
"validates_format_of" "validates_inclusion_of" "validates_length_of"
"validates_numericality_of" "validates_presence_of" "validates_size_of"
"validates_existence_of" "validates_uniqueness_of" "validates_with"
"enum" "after_create_commit" "after_update_commit" "after_destroy_commit")
"List of keywords to highlight for models."
:group 'projectile-rails
:type '(repeat string))
(defcustom projectile-rails-view-keywords
'("action_name" "atom_feed" "audio_path" "audio_tag" "auto_discovery_link_tag"
"button_tag" "button_to" "button_to_function" "cache" "capture" "cdata_section"
"check_box" "check_box_tag" "collection_select" "concat" "content_for"
"content_tag" "content_tag_for" "controller" "controller_name"
"controller_path" "convert_to_model" "cookies" "csrf_meta_tag" "csrf_meta_tags"
"current_cycle" "cycle" "date_select" "datetime_select" "debug"
"distance_of_time_in_words" "distance_of_time_in_words_to_now" "div_for"
"dom_class" "dom_id" "email_field" "email_field_tag" "escape_javascript"
"escape_once" "excerpt" "favicon_link_tag" "field_set_tag" "fields_for"
"file_field" "file_field_tag" "flash" "form_for" "form_tag"
"grouped_collection_select" "grouped_options_for_select" "headers"
"hidden_field" "hidden_field_tag" "highlight" "image_alt" "image_path"
"image_submit_tag" "image_tag" "j" "javascript_cdata_section"
"javascript_include_tag" "javascript_path" "javascript_tag" "l" "label"
"label_tag" "link_to" "link_to_function" "link_to_if" "link_to_unless"
"link_to_unless_current" "localize" "logger" "mail_to" "number_field"
"number_field_tag" "number_to_currency" "number_to_human" "number_to_human_size"
"number_to_percentage" "number_to_phone" "number_with_delimiter"
"number_with_precision" "option_groups_from_collection_for_select"
"options_for_select" "options_from_collection_for_select" "params"
"password_field" "password_field_tag" "path_to_audio" "path_to_image"
"path_to_javascript" "path_to_stylesheet" "path_to_video" "phone_field"
"phone_field_tag" "pluralize" "provide" "radio_button" "radio_button_tag"
"range_field" "range_field_tag" "raw" "render" "request"
"request_forgery_protection_token" "reset_cycle" "response" "safe_concat"
"safe_join" "sanitize" "sanitize_css" "search_field" "search_field_tag"
"select" "select_date" "select_datetime" "select_day" "select_hour"
"select_minute" "select_month" "select_second" "select_tag" "select_time"
"select_year" "session" "simple_format" "strip_links" "strip_tags"
"stylesheet_link_tag" "stylesheet_path" "submit_tag" "t" "tag" "telephone_field"
"telephone_field_tag" "text_area" "text_area_tag" "text_field" "text_field_tag"
"time_ago_in_words" "time_select" "time_tag" "time_zone_options_for_select"
"time_zone_select" "translate" "truncate" "url_field" "url_field_tag"
"url_for" "url_options" "video_path" "video_tag" "word_wrap")
"List of keywords to highlight for views."
:group 'projectile-rails
:type '(repeat string))
(defcustom projectile-rails-active-support-keywords
'("alias_attribute" "with_options" "delegate")
"List of keywords to highlight for all `projectile-rails-mode' buffers."
:group 'projectile-rails
:type '(repeat string))
(defvar projectile-rails-keyword-face 'projectile-rails-keyword-face
"Face name to use for keywords.")
(defface projectile-rails-keyword-face '((t :inherit 'font-lock-keyword-face))
"Face to be used for higlighting the rails keywords."
:group 'projectile-rails)
(defcustom projectile-rails-views-re
(concat "\\."
(regexp-opt '("html" "erb" "haml" "slim"
"js" "coffee" "ts"
"css" "scss" "less"
"json" "builder" "jbuilder" "rabl")))
"Regexp for filtering for view files."
:group 'projectile-rails
:type 'regexp)
(defcustom projectile-rails-javascript-re
"\\.js\\(?:\\.\\(?:coffee\\|ts\\)\\)?\\'"
"Regexp for filtering for Javascript/altJS files."
:group 'projectile-rails
:type 'regexp)
(defcustom projectile-rails-stylesheet-re
"\\.css\\(?:\\.\\(?:scss\\|sass\\|less\\)\\)?\\'"
"Regexp for filtering for stylesheet files."
:group 'projectile-rails
:type 'regexp)
(defcustom projectile-rails-errors-re
"\\([0-9A-Za-z@_./\:-]+\\.rb\\):?\\([0-9]+\\)?"
"The regex used to find errors with file paths."
:group 'projectile-rails
:type 'regexp)
(defcustom projectile-rails-generate-filepath-re
"^\\s-+\\(?:create\\|exists\\|conflict\\|skip\\)\\s-+\\(.+\\)$"
"The regex used to find file paths in `projectile-rails-generate-mode'."
:group 'projectile-rails
:type 'regexp)
(defcustom projectile-rails-javascript-dirs
'("app/assets/javascripts/" "lib/assets/javascripts/" "public/javascripts/")
"The list of directories to look for the javascript files in."
:group 'projectile-rails
:type '(repeat string))
(defcustom projectile-rails-component-dir "app/javascript/packs/"
"The directory to look for javascript component files in."
:group 'projectile-rails
:type 'string)
(defcustom projectile-rails-stylesheet-dirs
'("app/assets/stylesheets/" "lib/assets/stylesheets/" "public/stylesheets/")
"The list of directories to look for the stylesheet files in."
:group 'projectile-rails
:type '(repeat string))
(defcustom projectile-rails-expand-snippet t
"Automatically expand snippets in new buffers.
If not nil, function `auto-insert' will expand snippets
in the newly created buffers."
:group 'projectile-rails
:type 'boolean)
(defcustom projectile-rails-add-keywords t
"If not nil the rails keywords will be font locked in the mode's bufffers."
:group 'projectile-rails
:type 'boolean)
(defcustom projectile-rails-keymap-prefix nil
"Keymap prefix for `projectile-rails-mode'."
:group 'projectile-rails
:type 'string)
(make-obsolete-variable 'projectile-keymap-prefix "Use (define-key projectile-rails-mode-map (kbd ...) 'projectile-rails-command-map) instead." "0.20.0")
(defcustom projectile-rails-server-mode-ansi-colors t
"If not nil `projectile-rails-server-mode' will apply ansi colors in its buffer."
:group 'projectile-rails
:type 'boolean)
(defcustom projectile-rails-discover-bind "s-r"
"The :bind option that will be passed `discover-add-context-menu' if available."
:group 'projectile-rails
:type 'string)
(defcustom projectile-rails-vanilla-command "bundle exec rails"
"The command for rails."
:group 'projectile-rails
:type 'string)
(defcustom projectile-rails-spring-command "bundle exec spring"
"The command for spring."
:group 'projectile-rails
:type 'string)
(defcustom projectile-rails-zeus-command "zeus"
"The command for zeus."
:group 'projectile-rails
:type 'string)
(defcustom projectile-rails-root-file "Gemfile"
"The file that is used to identify rails root."
:group 'projectile-rails
:type 'string)
(define-obsolete-variable-alias 'projectile-rails-verify-root-file 'projectile-rails-verify-root-files "0.20.0")
(defcustom projectile-rails-verify-root-files '("config/routes.rb" "config/environment.rb")
"The list of files that is used to verify rails root directory.
When any of the files are found it means that this is a rails app."
:group 'projectile-rails
:type 'string)
(defcustom projectile-rails-custom-console-command nil
"Override the shell command used to run the rails console.
When set, this command will be used instead of a preloader."
:group 'projectile-rails
:type 'string)
(defcustom projectile-rails-custom-dbconsole-command nil
"Override the shell command used to run rails dbconsole.
When set, this command will be used instead of a preloader."
:group 'projectile-rails
:type 'string)
(defcustom projectile-rails-custom-server-command nil
"Override the shell command used to run rails server.
When set, this command will be used instead of a preloader."
:group 'projectile-rails
:type 'string)
(defcustom projectile-rails-custom-generate-command nil
"Override the shell command used to run rails generate.
When set, this command will be used instead of a preloader."
:group 'projectile-rails
:type 'string)
(defcustom projectile-rails-custom-destroy-command nil
"Override the shell command used to run rails destroy.
When set, this command will be used instead of a preloader."
:group 'projectile-rails
:type 'string)
(defcustom projectile-rails-expand-snippet-with-magic-comment nil
"Declare frozen string literals in every new ruby file.
When t, the new file snippets will be expanded with the magic comment
'frozen_string_literal: true'."
:group 'projectile-rails
:type 'boolean)
(defcustom projectile-rails-compilation-buffer-maximum-size 500
"Limit the size of the buffer used for rails server output.
The maximum size (in lines) of the compilation buffer used by
`projectile-rails-server'."
:group 'projectile-rails
:type 'integer)
(defvar projectile-rails-extracted-region-snippet
'(("erb" . "<%%= render '%s' %%>")
("haml" . "= render '%s'")
("slim" . "= render '%s'"))
"A template used to insert text after extracting a region.")
(defvar projectile-rails-server-buffer-name "*projectile-rails-server*")
(defvar projectile-rails-fixture-dirs
'("test/fixtures/" "test/factories/" "test/fabricators/"
"spec/fixtures/" "spec/factories/" "spec/fabricators/"))
(defvar-local projectile-rails-zeus-sock nil
"The path to the Zeus socket file.")
(defvar projectile-rails-generators
'(("assets" (("app/assets/"
"app/assets/\\(?:stylesheets\\|javascripts\\)/\\(.+?\\)\\..+$")))
("controller" (("app/controllers/" "app/controllers/\\(.+\\)_controller\\.rb$")))
("generator" (("lib/generator/" "lib/generators/\\(.+\\)$")))
("helper" (("app/helpers/" "app/helpers/\\(.+\\)_helper.rb$")))
("integration_test" (("test/integration/" "test/integration/\\(.+\\)_test\\.rb$")))
("job" (("app/jobs/" "app/jobs/\\(.+\\)_job\\.rb$")))
("mailer" (("app/mailers/" "app/mailers/\\(.+\\)\\.rb$")))
("migration" (("db/migrate/" "db/migrate/[0-9]+_\\(.+\\)\\.rb$")))
("model" (("app/models/" "app/models/\\(.+\\)\\.rb$")))
("resource" (("app/models/" "app/models/\\(.+\\)\\.rb$")))
("scaffold" (("app/models/" "app/models/\\(.+\\)\\.rb$")))
("task" (("lib/tasks/" "lib/tasks/\\(.+\\)\\.rake$")))))
(defun projectile-rails--command (&rest cases)
"Check for the presence of pre-loaders and return corresponding value.
CASES is a plist with props being :spring, :zeus or :vanilla.
Each corresponds to a preloader (:vanilla means no preloader).
If a preloader is running the value for the given prop is returned."
(let ((custom-command (plist-get cases :custom)))
(cond
(custom-command
(projectile-rails--ensure-suffix custom-command " "))
((projectile-rails-spring-p)
(plist-get cases :spring))
((projectile-rails-zeus-p)
(plist-get cases :zeus))
(t
(plist-get cases :vanilla)))))
(defalias 'projectile-rails-with-preloader 'projectile-rails--command)
(defmacro projectile-rails-with-root (body-form)
"Run BODY-FORM within DEFAULT-DIRECTORY set to `projectile-rails-root'."
`(let ((default-directory (projectile-rails-root)))
,body-form))
(defmacro projectile-rails-find-current-resource (dir re fallback)
"RE will be the argument to `s-lex-format'.
The bound variables are \"singular\" and \"plural\".
Argument DIR is the directory to which the search should be narrowed."
`(let* ((singular (projectile-rails-current-resource-name))
(plural (inflection-pluralize-string singular))
(abs-current-file (buffer-file-name (current-buffer)))
(current-file (if abs-current-file
(file-relative-name abs-current-file
(projectile-rails-root))))
(choices (projectile-rails-choices
(list (list ,dir (s-lex-format ,re)))))
(files (projectile-rails-hash-keys choices)))
(if (eq files ())
(funcall ,fallback)
(projectile-rails-goto-file
(if (= (length files) 1)
(gethash (-first-item files) choices)
(projectile-rails--choose-file-or-new choices files))))))
(defun projectile-rails--choose-file-or-new (choices files)
"Choose filename from FILES, or create new file from CHOICES."
(let* ((choice (projectile-completing-read "Which exactly: " files))
(candidate (gethash choice choices)))
(if (f-exists? (projectile-rails-expand-root candidate))
candidate
(concat (f-dirname (gethash (-first-item files) choices)) choice))))
(defun projectile-rails-spring-p ()
"Return t if spring is running."
(let ((root (directory-file-name (projectile-rails-root))))
(or
;; Older versions
(file-exists-p (format "%s/tmp/spring/spring.pid" root))
;; 0.9.2+
(file-exists-p (format "%s/spring/%s.pid" temporary-file-directory (md5 root)))
;; 1.2.0+
(let* ((path (or (getenv "XDG_RUNTIME_DIR") temporary-file-directory))
(ruby-version (shell-command-to-string "ruby -e 'print RUBY_VERSION'"))
(application-id (md5 (concat ruby-version root))))
(or
(file-exists-p (format "%s/spring/%s.pid" path application-id))
;; 1.5.0+
(file-exists-p (format "%s/spring-%s/%s.pid" path (user-real-uid) application-id)))))))
(defun projectile-rails-zeus-p ()
"Return t if zeus is running."
(unless projectile-rails-zeus-sock
(setq
projectile-rails-zeus-sock
(or (getenv "ZEUSSOCK") (projectile-rails-expand-root ".zeus.sock"))))
(file-exists-p projectile-rails-zeus-sock))
(defun projectile-rails-highlight-keywords (keywords)
"Highlight the passed KEYWORDS in current buffer."
(font-lock-add-keywords
nil
(list (list
(concat "\\(^\\|[^_:.@$]\\|\\.\\.\\)\\b"
(regexp-opt keywords t)
"\\_>")
(list 2 'projectile-rails-keyword-face)))))
(defun projectile-rails-add-keywords-for-file-type ()
"Apply extra font lock keywords specific to models, controllers etc."
(cl-loop for (re keywords) in `(("_controller\\.rb$" ,projectile-rails-controller-keywords)
("app/models/.+\\.rb$" ,projectile-rails-model-keywords)
("db/migrate/.+\\.rb$" ,projectile-rails-migration-keywords))
do (when (and (buffer-file-name) (string-match-p re (buffer-file-name)))
(projectile-rails-highlight-keywords
(append keywords projectile-rails-active-support-keywords)))))
(defun projectile-rails-dir-files (directory)
"Obsolete.
Wrapper around `projectile-dir-files', list the files in DIRECTORY
and in its sub-directories.
Files are returned as relative paths to DIRECTORY. This function
was created to handle the case when rails is inside a
subdirectory, but nowadays it does nothing as
`projectile-dir-files' does the right thing."
(projectile-dir-files directory))
(defun projectile-rails-choices (dirs)
"Use `projectile-rails-dir-files' function to find files in directories.
The DIRS is list of lists consisting of a directory path and
regexp to filter files from that directory. Optional third
element can be present in the DIRS list. The third element will
be a prefix to be placed before the filename in the resulting
choice. Returns a hash table with keys being short
names (choices) and values being relative paths to the files."
(let ((hash (make-hash-table :test 'equal)))
(cl-loop for (dir re prefix) in dirs do
(cl-loop for file in (projectile-rails-dir-files (projectile-rails-expand-root dir)) do
(when (string-match re file)
(puthash
(concat (or prefix "") (match-string 1 file))
(concat dir file)
hash))))
hash))
(defun projectile-rails-hash-keys (hash)
"Return the keys in HASH."
(if (boundp 'hash-table-keys)
(hash-table-keys hash)
(let (keys)
(maphash (lambda (key value) (setq keys (cons key keys))) hash)
keys)))
(defmacro projectile-rails-find-resource (prompt dirs &optional newfile-template)
"Presents files from DIRS with PROMPT to the user.
Uses `projectile-completing-read'.
If users chooses a non existant file and NEWFILE-TEMPLATE is not nil
it will use that variable to interpolate the name for the new file.
NEWFILE-TEMPLATE will be the argument for `s-lex-format'.
The bound variable is \"filename\"."
`(let ((choices (projectile-rails-choices ,dirs)))
(projectile-completing-read
,prompt
(projectile-rails-hash-keys choices)
:action (lambda (c)
(let* ((filepath (gethash c choices))
(filename c)) ;; so `s-lex-format' can interpolate FILENAME
(if filepath
(projectile-rails-goto-file filepath)
(when ,newfile-template
(projectile-rails-goto-file (s-lex-format ,newfile-template) t))))))))
(defun projectile-rails-find-model ()
"Find a model."
(interactive)
(projectile-rails-find-resource
"model: "
'(("app/models/" "\\(.+\\)\\.rb$"))
"app/models/${filename}.rb"))
(defun projectile-rails-find-controller ()
"Find a controller."
(interactive)
(projectile-rails-find-resource
"controller: "
'(("app/controllers/" "\\(.+?\\)\\(_controller\\)?\\.rb$"))
"app/controllers/${filename}_controller.rb"))
(defun projectile-rails-find-serializer ()
"Find a serializer."
(interactive)
(projectile-rails-find-resource
"serializer: "
'(("app/serializers/" "\\(.+\\)_serializer\\.rb$"))
"app/serializers/${filename}_serializer.rb"))
(defun projectile-rails-find-view ()
"Find a template or a partial."
(interactive)
(projectile-rails-find-resource
"view: "
`(("app/views/" ,(concat "\\(.+\\)" projectile-rails-views-re)))
"app/views/${filename}"))
(defun projectile-rails-find-layout ()
"Find a layout file."
(interactive)
(projectile-rails-find-resource
"layout: "
`(("app/views/layouts/" ,(concat "\\(.+\\)" projectile-rails-views-re)))
"app/views/layouts/${filename}"))
(defun projectile-rails-find-rake-task (arg)
"Find a file where a task is defined.
ARG is passed straight to function `rake-find-task'."
(interactive "P")
(rake-find-task arg))
(defun projectile-rails-find-helper ()
"Find a helper."
(interactive)
(projectile-rails-find-resource
"helper: "
'(("app/helpers/" "\\(.+\\)_helper\\.rb$"))
"app/helpers/${filename}_helper.rb"))
(defun projectile-rails-find-lib ()
"Find a file within lib directory."
(interactive)
(projectile-rails-find-resource
"lib: "
'(("lib/" "\\(.+\\)\\.rb$"))
"lib/${filename}.rb"))
(defun projectile-rails-find-spec ()
"Find a spec."
(interactive)
(projectile-rails-find-resource
"spec: "
'(("spec/" "\\(.+\\)_spec\\.rb$"))
"spec/${filename}_spec.rb"))
(defun projectile-rails-find-test ()
"Find a test."
(interactive)
(projectile-rails-find-resource
"test: "
'(("test/" "\\(.+\\)_test\\.rb$"))
"test/${filename}_test.rb"))
(defun projectile-rails-find-fixture ()
"Find a fixture file."
(interactive)
(projectile-rails-find-resource
"fixture: "
(--map (list it "\\(.+?\\)\\(?:_fabricator\\)?\\.\\(?:rb\\|yml\\)$")
projectile-rails-fixture-dirs)))
(defun projectile-rails-find-feature ()
"Find a feature file."
(interactive)
(projectile-rails-find-resource
"feature: "
'(("features/" "\\(.+\\)\\.feature$"))
"features/${filename}.feature"))
(defun projectile-rails-find-migration ()
"Find a migration."
(interactive)
(projectile-rails-find-resource "migration: " '(("db/migrate/" "\\(.+\\)\\.rb$"))))
(defun projectile-rails-find-javascript ()
"Find a javascript file."
(interactive)
(projectile-rails-find-resource
"javascript: "
(--map (list it "\\(.+\\)\\.[^.]+$") projectile-rails-javascript-dirs)))
(defun projectile-rails-find-component ()
"Find a javascript component."
(interactive)
(projectile-rails-find-resource
"component: "
`((,projectile-rails-component-dir "\\(.+\\.[^.]+\\)$"))))
(defun projectile-rails-find-stylesheet ()
"Find a stylesheet file."
(interactive)
(projectile-rails-find-resource
"stylesheet: "
(--map (list it "\\(.+\\)\\.[^.]+$") projectile-rails-stylesheet-dirs)) )
(defun projectile-rails-find-initializer ()
"Find an initializer file."
(interactive)
(projectile-rails-find-resource
"initializer: "
'(("config/initializers/" "\\(.+\\)\\.rb$"))
"config/initializers/${filename}.rb"))
(defun projectile-rails-find-environment ()
"Find an environment file."
(interactive)
(projectile-rails-find-resource
"environment: "
'(("config/" "\\(application\\|environment\\)\\.rb$")
("config/environments/" "\\(.+\\)\\.rb$" "environments/"))))
(defun projectile-rails-find-webpack ()
"Find a webpack configuration."
(interactive)
(projectile-rails-find-resource
"webpack config: "
'(("config/webpack/" "\\(.+\\.[^.]+\\)$"))))
(defun projectile-rails-find-locale ()
"Find a locale file."
(interactive)
(projectile-rails-find-resource
"locale: "
'(("config/locales/"
"\\(.+\\)\\.\\(?:rb\\|yml\\)$"))
"config/locales/${filename}"))
(defun projectile-rails-find-mailer ()
"Find a mailer."
(interactive)
(projectile-rails-find-resource
"mailer: "
'(("app/mailers/" "\\(.+\\)\\.rb$"))
"app/mailer/${filename}.rb"))
(defun projectile-rails-find-validator ()
"Find a validator."
(interactive)
(projectile-rails-find-resource
"validator: "
'(("app/validators/" "\\(.+?\\)\\(_validator\\)?\\.rb\\'"))
"app/validators/${filename}_validator.rb"))
(defun projectile-rails-find-job ()
"Find a job file."
(interactive)
(projectile-rails-find-resource
"job: "
'(("app/jobs/" "\\(.+?\\)\\(_job\\)?\\.rb\\'"))
"app/jobs/${filename}_job.rb"))
(defun projectile-rails-find-current-model ()
"Find a model for the current resource."
(interactive)
(projectile-rails-find-current-resource "app/models/"
"${singular}\\.rb$"
'projectile-rails-find-model))
(defun projectile-rails-find-current-controller ()
"Find a controller for the current resource."
(interactive)
(projectile-rails-find-current-resource "app/controllers/"
"\\(.*${plural}\\)_controller\\.rb$"
'projectile-rails-find-controller))
(defun projectile-rails-find-current-serializer ()
"Find a serializer for the current resource."
(interactive)
(projectile-rails-find-current-resource "app/serializers/"
"\\(.*${singular}\\)_serializer\\.rb$"
'projectile-rails-find-serializer))
(defun projectile-rails-find-current-view ()
"Find a template for the current resource."
(interactive)
(projectile-rails-find-current-resource "app/views/"
"${plural}/\\(.+\\)$"
'projectile-rails-find-view))
(defun projectile-rails-find-current-helper ()
"Find a helper for the current resource."
(interactive)
(projectile-rails-find-current-resource "app/helpers/"
"\\(${plural}_helper\\)\\.rb$"
'projectile-rails-find-helper))
(defun projectile-rails-find-current-javascript ()
"Find a javascript for the current resource."
(interactive)
(projectile-rails-find-current-resource "app/assets/javascripts/"
"\\(.*${plural}\\)${projectile-rails-javascript-re}"
'projectile-rails-find-javascript))
(defun projectile-rails-find-current-stylesheet ()
"Find a stylesheet for the current resource."
(interactive)
(projectile-rails-find-current-resource "app/assets/stylesheets/"
"\\(.*${plural}\\)${projectile-rails-stylesheet-re}"
'projectile-rails-find-stylesheet))
(defun projectile-rails-find-current-spec ()
"Find a spec for the current resource."
(interactive)
(if (fboundp 'rspec-toggle-spec-and-target)
(rspec-toggle-spec-and-target)
(projectile-find-test-file)))
(defun projectile-rails-find-current-test ()
"Find a test for the current resource."
(interactive)
(projectile-toggle-between-implementation-and-test))
(defun projectile-rails-find-current-fixture ()
"Find a fixture for the current resource."
(interactive)
(projectile-rails-find-current-resource
(cl-first projectile-rails-fixture-dirs)
"\\(?:${singular}\\(?:_fabricator\\)?\\|${plural}\\)\\.\\(?:yml\\|rb\\)"
'projectile-rails-find-fixture))
(defun projectile-rails-find-current-migration ()
"Find a migration for the current resource."
(interactive)
(projectile-rails-find-current-resource "db/migrate/"
"[0-9]\\{14\\}.*_\\(${plural}\\|${singular}\\).*\\.rb$"
'projectile-rails-find-migration))
(defcustom projectile-rails-resource-name-re-list
`("/app/models/\\(?:.+/\\)?\\(.+\\)\\.rb\\'"
"/app/controllers/\\(?:.+/\\)?\\(.+\\)_controller\\.rb\\'"
"/app/views/\\(?:.+/\\)?\\([^/]+\\)/[^/]+\\'"
"/app/helpers/\\(?:.+/\\)?\\(.+\\)_helper\\.rb\\'"
,(concat "/app/assets/javascripts/\\(?:.+/\\)?\\(.+\\)" projectile-rails-javascript-re)
,(concat "/app/assets/stylesheets/\\(?:.+/\\)?\\(.+\\)" projectile-rails-stylesheet-re)
"/db/migrate/.*create_\\(.+\\)\\.rb\\'"
"/spec/.*/\\([a-z_]+?\\)\\(?:_controller\\)?_spec\\.rb\\'"
"/test/.*/\\([a-z_]+?\\)\\(?:_controller\\)?_test\\.rb\\'"
"/\\(?:test\\|spec\\)/\\(?:fixtures\\|factories\\|fabricators\\)/\\(.+?\\)\\(?:_fabricator\\)?\\.\\(?:yml\\|rb\\)\\'")
"List of regexps for extracting a resource name from a buffer file name."
:group 'projectile-rails
:type '(repeat regexp))
(defun projectile-rails-current-resource-name ()
"Return a resource name extracted from the name of the currently visiting file."
(let* ((file-name (buffer-file-name))
(name (and file-name
(cl-loop for re in projectile-rails-resource-name-re-list
do (if (string-match re file-name)
(cl-return (match-string 1 file-name)))))))
(and name
(inflection-singularize-string name))))
(defun projectile-rails-list-entries (fun dir)
"Call FUN on DIR being a relative directory within a rails project.
It is suspected that the result of FUN will be a list of filepaths.
Each filepath will have the path to the project discarded."
(--map
(substring it (length (concat (projectile-rails-root) dir)))
(funcall fun (projectile-rails-expand-root dir))))
(defun projectile-rails-find-log ()
"Find a log file.
The opened buffer will have `auto-revert-tail-mode' turned on."
(interactive)
(let ((logs-dir (cl-loop for dir in '("log/" "spec/dummy/log/" "test/dummy/log/")
until (projectile-rails--file-exists-p dir)
finally return dir)))
(unless logs-dir
(user-error "No log directory found"))
;;logs tend to not be under scm so do not resort to projectile-dir-files
(find-file (projectile-rails-expand-root
(concat
logs-dir
(projectile-completing-read
"log: "
(projectile-rails-list-entries 'f-files logs-dir)))))
(auto-revert-tail-mode +1)
(setq-local auto-revert-verbose nil)
(buffer-disable-undo)
(projectile-rails-on)))
(defun projectile-rails-rake (arg)
"Run a rake task.
ARG will be passed to `rake' interactive command.
The mode of the output buffer will be `projectile-rails-compilation-mode'."
(interactive "P")
(rake arg 'projectile-rails-compilation-mode))
(defvar projectile-rails-cache-data
(make-hash-table :test 'equal)
"A hash table that is used for caching information about the current project.")
(defun projectile-rails-cache-key (key)
"Generate a cache key based on the current directory and the given KEY."
(format "%s-%s" default-directory key))
(defun projectile-rails--rails-app-p (root)
"Determine if the project at ROOT is a Rails project.
Returns t if any of the relative files in
`projectile-rails-verify-root-files' is found.
ROOT is used to expand the relative files."
(--any-p
(file-exists-p (expand-file-name it root))
(-list projectile-rails-verify-root-files)))
(defun projectile-rails-root ()
"Locate the root directory of the current Rails project.
Return the root directory if this file is a part of a
Rails application, else nil."
(let* ((cache-key (projectile-rails-cache-key "root"))
(cache-value (gethash cache-key projectile-rails-cache-data)))
(or cache-value
(ignore-errors
(let ((root (projectile-locate-dominating-file default-directory projectile-rails-root-file)))
(when (projectile-rails--rails-app-p root)
(puthash cache-key root projectile-rails-cache-data)
root))))))
(defun projectile-rails-root-relative-to-project-root ()
"Return the Rails root directory relative to variable `projectile-project-root'."
(let ((rails-root (file-truename (projectile-rails-root)))
(project-root (projectile-project-root)))
(if (string-equal rails-root project-root)
""
(substring rails-root (length (f-common-parent (list rails-root project-root)))))))
(defun projectile-rails-expand-root (dir)
"Like `projectile-expand-root' (expands DIR)
but consider `projectile-rails-root'."
(projectile-expand-root (concat (projectile-rails-root) dir)))
(defun projectile-rails--file-exists-p (filepath)
"Return t if relative FILEPATH exists within current project."
(file-exists-p (projectile-rails-expand-root filepath)))
(defun projectile-rails-console (arg)
"Start a rails console, asking for which if ARG is not nil."
(interactive "P")
(projectile-rails-with-root
(let ((rails-console-command (projectile-rails--command
:custom projectile-rails-custom-console-command
:spring (concat projectile-rails-spring-command " rails console")
:zeus "zeus console"
:vanilla (concat projectile-rails-vanilla-command " console"))))
(when (inf-ruby--irb-needs-nomultiline-p)
(setq rails-console-command (concat rails-console-command " -- --nomultiline")))
(with-demoted-errors
(inf-ruby-console-run
(if (>= (or (car arg) 0) 4)
(read-string "rails console: " rails-console-command)
rails-console-command)
"rails"))
(projectile-rails-mode +1))))
;; Shamelessly stolen from rinari.el
(defun projectile-rails--db-config ()
"Return contents of config/database.yml as a list."
(json-read-from-string
(shell-command-to-string
(format
"ruby -ryaml -rjson -e 'JSON.dump(YAML.load(ARGF.read), STDOUT)' \"%s\""
(projectile-rails-expand-root "config/database.yml")))))
(defvar projectile-rails--sql-adapters->products
'(("mysql2" "mysql")
("mysql" "mysql")
("jdbcmysql" "mysql")
("postgres" "postgres")
("postgresql" "postgres")
("jdbcpostgresql" "postgres")
("sqlite" "sqlite")
("sqlite3" "sqlite")
("jdbcsqlite3" "sqlite")
("informix" "informix")
("ingres" "ingres")
("interbase" "interbase")
("linter" "linter")
("ms" "ms")
("oracle" "oracle")
("solid" "solid")
("sybase" "sybase")
("vertica" "vertica"))
"Mapping between ruby libraries and Emacs sql adapters.")
(defun projectile-rails--determine-sql-product (env)
"Return Emacs sql adapter that should be used for the given project.
ENV is the name of the rails environment."
(intern
(car
(cdr
(assoc-string (cdr (assoc-string "adapter" (cdr (assoc-string env (projectile-rails--db-config)))))
projectile-rails--sql-adapters->products)))))
(defun projectile-rails--choose-env ()
"Return rails environment to use.
The candidates are based on the files found in config/environments/"
(projectile-completing-read
"Choose env: "
(--map (substring it 0 -3)
(projectile-rails-list-entries 'f-files "config/environments/"))))
(defun projectile-rails-dbconsole ()
"Run rails-dbconsole command.
The buffer for interacting with SQL client is created via
`sql-product-interactive'."
(interactive)
(require 'sql)
(projectile-rails-with-root
(let* ((env (projectile-rails--choose-env))
(product (projectile-rails--determine-sql-product env))
(sqli-login (sql-get-product-feature product :sqli-login))
(sqli-options (sql-get-product-feature product :sqli-options))
(sqli-program (sql-get-product-feature product :sqli-program))
(sql-comint-func (sql-get-product-feature product :sqli-comint-func))
(commands (s-split " " (projectile-rails--command
:custom projectile-rails-custom-dbconsole-command
:spring (concat projectile-rails-spring-command " rails dbconsole")
:zeus (concat projectile-rails-zeus-command " dbconsole")
:vanilla (concat projectile-rails-vanilla-command " dbconsole")))))
(sql-set-product-feature product :sqli-login '())
(sql-set-product-feature product :sqli-options '())
(sql-set-product-feature product :sqli-program (car commands))
(sql-set-product-feature product :sqli-comint-func (lambda (_ __ &optional buf-name)
(sql-comint product (cdr commands) buf-name)))
(sql-product-interactive product)
(sql-set-product-feature product :sqli-comint-func sql-comint-func)
(sql-set-product-feature product :sqli-program sqli-program)
(sql-set-product-feature product :sqli-options sqli-options)
(sql-set-product-feature product :sqli-login sqli-login))))
(defun projectile-rails--auto-insert-setup-p (current-project-cond)
"Check if Auto-insert mode is active.
Return t if passed CURRENT-PROJECT-COND has been activated
with function `define-auto-insert'."
(seq-some
(pcase-lambda (`(,cond . ,action))
(equal current-project-cond cond))
auto-insert-alist))
(defun projectile-rails--setup-auto-insert ()
"Activate auto-insertion for all ruby files in the project.
Call `define-auto-insert' with condition for ruby files
under the current project.
If `auto-insert-alist' holds already the condition for the
current project it does nothing. So it safe to call it many times
like in a minor mode hook."
(let* ((file-re (format "^%s.*\\.rb$" (projectile-rails-root)))
(current-project-cond `(,file-re . "projectile-rails")))
(unless (projectile-rails--auto-insert-setup-p current-project-cond)
(define-auto-insert
current-project-cond
[
(lambda ()
(let ((snippet (projectile-rails-corresponding-snippet)))
(when snippet
(insert snippet))))
projectile-rails-expand-yas-buffer
]
))))
(defun projectile-rails-setup-auto-insert-maybe ()
"Setup Auto-insert mode for the current project.
In order to expand snippet in newly created buffers variable
`projectile-rails-expand-snippet' needs to be non-nil
and `auto-insert-mode' enabled."
(when (and projectile-rails-expand-snippet
(fboundp 'yas-expand-snippet)