Skip to content

Commit 535af4e

Browse files
author
Po Chen
committed
Fix and improve new module creation
1 parent de7160e commit 535af4e

File tree

2 files changed

+89
-69
lines changed

2 files changed

+89
-69
lines changed

RSpecCreateModule.py

+77-56
Original file line numberDiff line numberDiff line change
@@ -1,69 +1,90 @@
11
import sublime, sublime_plugin, time
22
import re
3-
from RSpec import shared
43

5-
_patterns = dict((k, re.compile('_*' + v)) for (k, v)
6-
in dict(allcamel=r'(?:[A-Z]+[a-z0-9]*)+$',
7-
trailingcamel=r'[a-z]+(?:[A-Z0-9]*[a-z0-9]*)+$',
8-
underscores=r'(?:[a-z]+_*)+[a-z0-9]+$').items())
4+
from textwrap import dedent
5+
from RSpec.shared import other_group_in_pair
96

10-
_caseTransition = re.compile('([A-Z][a-z]+)')
117

12-
def translate(name, _from, to):
13-
leading_underscores = str()
14-
while name[0] == '_':
15-
leading_underscores += '_'
16-
name = name[1:]
8+
def snake_case(name):
9+
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
10+
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
1711

18-
if _from in ('allcamel', 'trailingcamel'):
19-
words = _caseTransition.split(name)
20-
else:
21-
words = name.split('_')
2212

23-
words = list(w for w in words if w is not None and 0 < len(w))
13+
class GotoLineCommand(sublime_plugin.TextCommand):
2414

25-
camelize = lambda words: ''.join(w[0].upper() + w[1:] for w in words)
15+
def run(self, edit, line, column=0):
16+
pt = self.view.text_point(line - 1, column)
2617

27-
v = dict(smushed=lambda: ''.join(words).lower(),
28-
allcamel=lambda: camelize(words),
29-
trailingcamel=lambda: words[0].lower() + camelize(words[1:]),
30-
underscores=lambda: '_'.join(words).lower())[to]()
18+
self.view.sel().clear()
19+
self.view.sel().add(sublime.Region(pt))
3120

32-
return leading_underscores + v
21+
self.view.show(pt)
22+
23+
24+
class RspecNewModuleCommand(sublime_plugin.TextCommand):
25+
26+
def run(self, edit, name, namespace):
27+
class_template = dedent('''
28+
class {name}
29+
30+
end
31+
'''.lstrip('\n').rstrip(' \n').format(name=name))
32+
33+
module_template = dedent('''
34+
module {module}
35+
{definition}
36+
end
37+
'''.lstrip('\n').rstrip(' \n'))
38+
39+
template, level = class_template, len(namespace)
40+
41+
while namespace:
42+
module = namespace.pop()
43+
template = module_template.format(module=module, definition=self.indent(template))
44+
45+
self.view.insert(edit, 0, template)
46+
self.view.run_command('goto_line', { 'line': 2 + level, 'column': level * 2 })
47+
48+
def indent(self, text, space=2):
49+
return '\n'.join(' ' * space + line for line in text.split('\n'))
50+
51+
52+
class RspecNewSpecCommand(sublime_plugin.TextCommand):
53+
54+
def run(self, edit, name):
55+
template = dedent('''
56+
require 'spec_helper'
57+
58+
describe {name} do
59+
60+
end
61+
'''.strip('\n').format(name=name))
62+
63+
self.view.insert(edit, 0, template)
64+
self.view.run_command('goto_line', { 'line': 4 })
3365

3466

3567
class RspecCreateModuleCommand(sublime_plugin.WindowCommand):
36-
def run(self):
37-
# self.view.insert(edit, 0, "Hello, World!")
38-
self.window.show_input_panel("Enter module name:", "", self.on_done, None, None)
39-
40-
def on_done(self, text):
41-
42-
# create the module
43-
module = self.window.new_file()
44-
module.set_syntax_file('Packages/Ruby/Ruby.tmLanguage')
45-
module.set_name(translate(text, 'allcamel', 'underscores') + '.rb')
46-
module_template = "\n\
47-
class " + text + "\n\
48-
end"
49-
edit = module.begin_edit()
50-
module.insert(edit, 0, module_template)
51-
module.end_edit(edit)
52-
53-
# create the spec
54-
spec = self.window.new_file()
55-
self.window.run_command('move_to_group', {'group': shared.other_group_in_pair(self.window)})
56-
spec.set_syntax_file('Packages/Ruby/Ruby.tmLanguage')
57-
spec.set_name(translate(text, 'allcamel', 'underscores') + '_spec.rb')
58-
spec_template = "require 'spec_helper'\n\
59-
require '" + translate(text, 'allcamel', 'underscores') + "'\n\n\
60-
describe " + text + " do\n\
61-
\tit \"should do something\"\n\
62-
end"
63-
edit = spec.begin_edit()
64-
spec.insert(edit, 0, spec_template)
65-
spec.end_edit(edit)
66-
67-
# try:
68-
# except ValueError:
69-
# pass
68+
69+
def run(self):
70+
self.window.show_input_panel("Enter module name:", "", self.on_done, None, None)
71+
72+
def on_done(self, text):
73+
if not text: return
74+
75+
*namespace, name = re.split(r'/|::', text.strip(' _/'))
76+
77+
# create the module
78+
module = self.window.new_file()
79+
module.set_syntax_file('Packages/Ruby/Ruby.tmLanguage')
80+
module.set_name(snake_case(name) + '.rb')
81+
82+
module.run_command('rspec_new_module', { 'name': name, 'namespace': namespace })
83+
84+
# create the spec
85+
spec = self.window.new_file()
86+
self.window.run_command('move_to_group', { 'group': other_group_in_pair(self.window) })
87+
spec.set_syntax_file('Packages/Ruby/Ruby.tmLanguage')
88+
spec.set_name(snake_case(name) + '_spec.rb')
89+
90+
spec.run_command('rspec_new_spec', { 'name': '::'.join(namespace + [name]) })

RSpecDetectFileType.py

+12-13
Original file line numberDiff line numberDiff line change
@@ -2,28 +2,27 @@
22
import os
33

44
class RSpecDetectFileTypeCommand(sublime_plugin.EventListener):
5-
""" Detects current file type if the file's extension isn't conclusive """
6-
""" Modified for Ruby on Rails and Sublime Text 2 """
7-
""" Original pastie here: http://pastie.org/private/kz8gtts0cjcvkec0d4quqa """
5+
'''
6+
Detects current file type if the file's extension isn't conclusive
7+
Modified for Ruby on Rails and Sublime Text 2
8+
Original pastie here: http://pastie.org/private/kz8gtts0cjcvkec0d4quqa
9+
'''
810

911
def on_load(self, view):
1012
filename = view.file_name()
11-
if not filename: # buffer has never been saved
12-
return
13+
14+
if not filename: return # not saved
1315

1416
name = os.path.basename(filename.lower())
15-
if name[-8:] == "_spec.rb":
16-
set_syntax(view, "RSpec", "RSpec")
17+
if name.endswith("_spec.rb"):
18+
set_syntax(view, "RSpec")
1719
elif name == "factories.rb":
18-
set_syntax(view, "RSpec", "RSpec")
19-
# elif name == "gemfile":
20-
# set_syntax(view, "Ruby on Rails", "Rails")
21-
# elif name[-2:] == "rb":
22-
# set_syntax(view, "Ruby on Rails", "Rails")
20+
set_syntax(view, "RSpec")
2321

2422

2523
def set_syntax(view, syntax, path=None):
2624
if path is None:
2725
path = syntax
26+
2827
view.settings().set('syntax', 'Packages/'+ path + '/' + syntax + '.tmLanguage')
29-
print("Switched syntax to: " + syntax)
28+
print("Switched syntax to: " + syntax)

0 commit comments

Comments
 (0)