Sublime text настройка для ruby
I’ve been a satisfied Sublime user for the past three years, using it primarily for Rails development. Here are the packages, preferences, and tips I recommend for getting the most out of this excellent editor.
Published April 13, 2015
Revised August 22, 2016: Added the “CloseOtherWindows” package as suggested by reader Adrian. Thanks for the tip!
These recommendations are for Sublime Text 3, which is currently in beta, but stable. I’ll keep this article updated as my Sublime preferences change over time. You can also peek at my latest Sublime Text settings files and snippets by browsing my dotfiles repository on GitHub. Enjoy!
Settings
Packages aside, there are a bunch of built-in settings that I like to tweak to make Sublime work great as a Rails editor. Here are the important ones:
Indexing. This is one setting that deserves a special note. I always thought that source code indexing required a fancy IDE or a separate plugin, like ctags. But no! Sublime Text 3 does indexing, and it works great with Ruby. Just make sure it is turned on:
Place the cursor on a method call and use Goto Definition… to jump to the source. In my key mappings I’ve set this to ⌥ opt ⌘ cmd r .
Ruby-specific word selection behavior. When you double-click a word, or use any other word-related text selection commands, Sublime tries to be smart about where words begin and end. By default, it assumes punctuation is not part of the word. But in Ruby, punctuation can be part of method names: e.g. empty? and chomp! , among many others.
To tell Sublime to include those trailing ? and ! characters in word selections, add the following property to the Ruby syntax-specific settings. This has a side-effect of improving the Dash ⌃ ctrl h behavior as well!
(To get to the Ruby settings, open a Ruby file in the editor and then navigate the menus to Sublime Text → Preferences → Settings – More → Syntax Specific – User.)
Key mappings
For the most part, I am happy with Sublime’s default key mappings. There are just a few instances where I’ve tweaked the mappings to make them more consistent with other Mac editors like TextMate and Sublime.
I also like changing the behavior of ⌘ cmd v so that it does paste-and-indent, which is what I want 99% of the time.
About
Hi! I’m a freelance web developer helping startups design and launch great SaaS products using Ruby on Rails.
I’d love to hear your questions or comments on this article: just mention me on Twitter or drop me an email. Thanks! —m
Редактор Sublime Text, как известно, поддается детальнейшей настройке, благодаря чему ему можно придать любую желаемую внешность и кастомизировать под себя его поведение при работе. При написании кода на Ruby принятно придерживаться определенных практик, которые позволяют увеличить читабельность кода. Частично в этом мне помогает как раз сам редактор. Опишу несколько пунктов из его конфигурации, которые позволяют мне не задумываться о том, что нужно поставить лишний перевод строки или сделать софт-таб длиной в два пробела.
Редактируем файл пользовательских настроек, он же Preferences -> Settings – User.
Автоматическая закрывалка HTML-тегов. Иногда бывает полезно. Работает так: открыли тег, написали его содержимое, а чтобы закрыть тег просто пишем , после чего ST автоматом подставляет остальное.
Автозавершение вводимого текста. Включено по-умолчанию, но вдруг нет.
Автоматическая подстановка отступа. Если открыли написание метода или условие if, то редактор сам отодвинет курсор на размер табуляции.
Это просто название шрифта, который будет использоваться для кода. Иногда хочется сменить.
Визуально подсвечивает строку, на которой находится курсор. Удобно.
Эта конструкция подскажет редактору, чтобы он отображал вертикальную линию после 80-го символа. Поскольку Rails Best Practices предполагает, что писать строки длиннее 80 символов (стандартная ширина окна терминала) некрасиво и нечитабельно, стоит установить эту настройку.
Просто опция для отображения кодировки в правом нижнем углу окна редактора. Редко, но все же бывает полезно, чаще всего актуально при работе с PHP-файлами.
Очень полезная опция, изменяющая длину вставляемой табуляции на 2 пробела. По-умолчанию ST ставит длину табуляции равной четырем пробелам, что не соответствует Rails Best Pracices и вообще выглядит коряво.
Эта настройка делает табуляции, которые вы вставляете кнопкой Tab, двумя (в соответствии с предыдущим пунктом) пробелами, а не одним символом. Это полезно, это удобно, это нужно использовать. Вы же не хотите, чтобы ваш код у другого разработчика выглядел иначе, чем у вас, верно?
Прелестная опция, которая, в момент сохранения файла, устраняет все пробелы-хвосты, которые вы могли поставить случайно.
В момент сохранения файла добавляет в конец пустую строку. Тоже из Бест Практисес, рекомендую.
As far as standards go PHP has PSR, python has PEP and Ruby has. Well, ruby doesn't really have an established best practices and standards document like the other two languages. Luckily, we do have two excellent coding guides and a gem little called Rubocop that help fill the gap.
Thanks to the awesome work of Bozhidar Batsov and many talented folks, we have an unofficial Ruby and Rails coding standards documentation. These are great resources for when you have questions concerning object oriented programming design challenges. Additionally, they also built the super useful Rubocop gem for automating style checks.
I suggest that you read through, or at least skim through, some of the suggested standards. These were created by some of the top people in the industry and are really great for becoming a Ruby master. Some of the standards proposed can be directly translated into a Sublime Text configuration file which we will now begin to build.
"End each file with a newline."
Custom theme and icon
The “Primer” theme. I prefer a light theme for my editor, and Primer is by far the most polished (it’s the one you see in all the screenshots above). It also fits nicely with the OS X Yosemite look and feel. To use it, just install Primer using Package Control and follow the instructions that appear. I’ve also customized the theme a bit further with these settings:
Custom icon. Finally, I’ve replaced the default Sublime Text icon with something a bit more contemporary, designed by the talented Rafael Conde. You can download his icon from Dribbble.
A stylish alternative to the default Sublime icon.
To install the icon, first locate the Sublime Text application in the Finder and press ⌘ cmd i . Then drag and drop Rafael’s Sublime Text.icns file onto icon section of the Get Info window. If Sublime is in your Dock, you may need to restart the Dock process for the new icon to appear.
And that’s it! You made it to the end of my Sublime Text 3 setup guide. Thanks for reading!
"Use two spaces per indentation level (aka soft tabs). No hard tabs."
Unlike the PHP world of 4 spaces, Ruby developers generally use 2 spaces for indentation. I find this leads to more compact and readable code.
"They'll fix you. They fix everything." Rubocop
In addition to the standards documents, the team behind them also created the Rubocop gem. Rubocop is like the ruby linter on steroids as it churns through your code unapologetically telling you what needs to be fixed according to the unofficial coding standards. Similiar to PHP's PSR-fixer, Rubocop can be setup to run in the background or manually at your leisure.
This tells Rubocop to in addition to running the regular Ruby style cops (syntax checkers) to also run the Rails cops as well. You can find additional documentation on Sublimelinter-rubocop here and Rubocop itself documentation here.
Packages
Did you know that there is a fantastic online repository and discovery tool for Sublime Text packages? The plugin community for Sublime is huge, and there are more packages being added all the time. Here are the handful of packages that I consider must-haves for Rails development.
Of course, make sure you have Package Control installed first!
AdvancedNewFile. I use AdvancedNewFile to quickly create files at any level of a project folder hierarchy without needing to take my hands off the keyboard. This is really useful for Rails, where even a brand new project contains dozens of directories.
Just press ⌥ opt ⌘ cmd n and type the path (relative to the root of your project) of the file you want to create and press ⏎ return . AdvancedNewFile supports tab-completion, so you can quickly expand existing directory names.
Protip: if you prefix your path with the : character, AdvancedNewFile will create the file in the same directory as your current Sublime editor tab. (Note: I’m using the Primer theme in these screen recordings.)
All Autocomplete. Sublime ships with autocomplete behavior, but it is limited to completing strings that exist in the current editor. With All Autocomplete installed, all open files are searched for autocompletion candidates.
Clipboard Manager. Programming involves lots of copy and paste, so I consider clipboard history to be essential. There are system-wide solutions, but Clipboard Manager gets the job done for Sublime Text. It keeps a history of all copied text, and allows me to use keyboard shortcuts to browse that history or to cycle through previously copied text.
CloseOtherWindows. It’s easy for tabs to get out of control, so I like to activate a “focus mode” where I close all tabs except the one I’m working on. CloseOtherWindows provides exactly such a command, which you can activate with a right-click, or assign a keyboard shortcut. I use to ⇧ shift ⌘ cmd w (see my key mappings below).
DashDoc. I’m a big fan of Dash, which is a programming documentation browser for the Mac. Assuming Dash is installed, I can simply press ⌃ ctrl h in a Sublime editor and DashDoc immediately opens Dash to show the appropriate documentation based on the cursor position.
Don’t remember all the options for has_and_belongs_to_many ? Just press ⌃ ctrl h .
Emmet. I write my Rails views with ERB-flavored HTML, so Emmet is an incredible time-saver. The headline feature is that it makes writing complex nested markup super easy, but it has expansions and auto-completion for writing CSS/SCSS as well. There’s too much to explain in detail here, so be sure to check out the Emmet docs.
Emmet expands CSS-ish expressions into full-blown HTML markup. Just press ⇥ tab .
GitGutter. Shows what lines I’ve changed, added, or removed in comparison to the local git repository. GitGutter is a no-brainer if you use git.
Uncommitted changes show up in the gutter of the editor. No need to run git diff !
Rubocop style violations in yellow. (If there were Ruby syntax errors, they would appear in red.)
Snippets
Unlike TextMate, where I was always creating snippets and coding up customizations, Sublime Text and its powerful assortment of community-supplied packages do almost everything I need with minimal fuss. The built-in Ruby and Rails syntaxes and snippets are great.
There’s really just one notable case where I’ve needed to open the hood and add my own stuff.
Singleton class snippet. I’m always forgetting how to open the singleton class (eigenclass) in Ruby. The syntax just doesn’t come naturally to me: class
"Use Unix-style line endings."
Like I mentioned in my other article, How to configure Sublime Text for PSR Standards, utilizing unix line endings helps to keep all developers on the same page when using version control.
"Thank you for your co-operation. Good night."
All Robocop quotes aside, by using the above setup you can prevent some of the common syntax pitfalls with Ruby. In addition to the automated setup reading the two unofficial guides can be a lifesaver in determining what method to use or how to structure an application.
Was there an additional setting I missed? How about another tool or gem you use to help you follow standards? Maybe a completely different standard? I would love to hear about them in a comment below. Justice has been served.
У меня установлены плагины
All Autocomplete Сама ST3 также имеет автоматическое завершение, но этот плагин может значительно укрепить эту функцию.
SideBarEnhancements Усилить функцию боковой панели
Origami Усилить функцию оценки.Origami
markdownФункция: установкаMarkdown Editing После подключаемого плагина создайте файл Markdown, нажмите на приглашение формата файла в правом нижнем углу, выберите «Синтаксис MarkDown», используемый в разметке, редактирование в всплывающем меню, обычно используя MultiMarkdown. УстановитьMarkdown Preview Плагин, затем сделайте следующее command+shift+p — preview in browser — markdown / github Вы можете просмотреть файл Markdown в вашем браузере.
Рубокоп и Сублимелин После установки редактор будет следоватьruby-style-guide Стандарт проверяет ваш код, дает запрос кода, который не соответствует стандарту. Эта функция исходит отrubocop Первый gem install rubocop Установить этот драгоценный камень. Затем установите три плагина в ST3, чтобы реализовать автоматическую работу Rubocop на заднем плане:SublimeLinter 、SublimeLinter-Ruby иSublimeLinter-rubocop 。
Время SublimeLinter по умолчанию автоматически проверяет код для 0,1с, это слишком быстро, вы просто постучать в последнюю часть кода, это было бы ошибкой. Адаптации rubocop время отклика методы состоит в том, чтобы ST3-Preferences-пакеты Настройка-SublimeLinter-Настройка в открытом файле SublimeLinter.sublime-настройке, добавьте следующие параметры, время отклика будет установлена в 1 сек:
CTags CTags индекс весь код, расширенные классы, функции и т.д. функции перехода.
Во-первых, вилка в смонтированном CTags ST3, то терминал выполняет brew install ctags 。
Если вы хотите, чтобы построить индекс функции вашего проекта, как это определено, просто перейдите в каталог проекта в терминале, выполнение ctags -R -f .tags Создаст А. .tags Файл, индекс необходимо построить этот проект записывается в него.
Поскольку Rails проекта использовать много драгоценных камней, если вы хотите одновременно построить все индекс камень, используемый, вы можете создать файл сценария с именем ctags_for_ruby в вашем $ PATH каталог и выполнить chmod +x ctags_for_ruby Команда установит его на исполняемые файлы. Пишет следующее в файле:
воплощать в жизнь ctags_for_ruby Команда для выполнения этого скрипта, и создаст индекс .tags файл для функций проекта, создаст отдельный файл индекса для всех .gemtags драгоценного камня в корне каталоге с исходным.
Затем переместите курсор на имя функции в проекте, право Goto Definition Перейти к определению функции, право Jump Back Вы можете прыгать назад.
Мы, конечно, не хотим .tags контента и .gemtags появляется файл в результатах поиска полнотекстовых, метод устанавливается для ввода параметров ST3-Настройки-, в Preferences.sublime-settings——User Файл, добавив следующие параметры: "file_exclude_patterns": [".tags", ".tags_sorted_by_file", ".gemtags"]
"You have the right to remain silent." Multiple Sublime configurations
Since, most developers are more or less polyglot's when it comes to programming languages, separating our different coding standards becomes a must. Fortunately, for us Sublime Text 3 has a nifty feature for creating syntax specific user configuration files.
Under the preferences menu in the Settings - More menu you will see the option for Syntax Specific user configuration. By selecting this option Sublime Text will take your currently active file's code syntax and create a config file specific to it (e.g. JSON.sublime-settings). This file will then only be applicable to files that are also using this language syntax.
Create the ruby specific user configuration by clicking the Syntax Specific - User option and then renaming the file to Ruby.sublime-settings . Once created we can now start following the proposed Ruby style guide.
"Limit lines to 80 characters."
By setting the ruler to 80 and word wrap to true, we can impose a soft limit of 80 characters on a file.
Установите Sublime Text 3 (ST3)
оказаться Официальный сайт Sublime, Нажмите Загрузить в правом верхнем углу, выберите версию соответствующей версии вашей среды для загрузки. Если вы хотите установить Sublime Text 2, вы можете пойти сюда.Sublime Text 2 。
редактировать
грести выберите команду + L (нажмите несколько раз добавляемые к следующей строке выбора) команды + D выбрать слово (множественный выбор слово повторяется нажмите на ту же мультиплекс редактирование)
Команда + Shift + V вставка и автоматически втянута
Команда + Shift + S, чтобы сохранить все файлы
Фоновое введение
У меня нет ни одного фона, некоторые - просто спина. Отказ Отказ
Он использовался более двух лет, чтобы развить рельсы.Редактор атом Я чувствую себя очень простым в использовании. Приходите к новой компании, большинство коллег используют возвышенную, чтобы лучше сотрудничать с вами, я буду «проводить курс».
Используется в течение двух недель: «Я чувствую, что талия не является кислым, ноги не больно», качество кода улучшилось.
Быстро, особенно быстро, воры: почти без коробки, особенно при прыжках к определению функции, я даже чувствую себя слишком быстро от атома.
Изменение конфигурации более подходит для программистов: я всегда решил, что основное преимущество атома является визуальным интерфейсом при установке плагина, и операция проще. Но теперь я чувствую, что все JSON будут изменены и настроены.
Лучше поддержать Markdown не так хорошо, как атом, или это может быть, что я не нашел лучший плагин. Нужно установить несколько плагинов, это более неприятно.
Ниже я устанавливаю меня, настроив яму, встречающуюся в возвышенном процессе, и наслаждайтесь отмыванием.
"Avoid trailing whitespace."
Another setting that teams of developers will all need to use to avoid git conflicts. Kill the whitespace!
Используйте командную строку, чтобы открыть ST3
воплощать в жизнь ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl Терминал может быть выполнен subl projet_name Чтобы открыть проект с кодом ST3.
Профиль
ST3-Preferences-Настройка, чтобы открыть файл конфигурации. Файл конфигурации ST3 есть два, один по умолчанию, является Пользователем. Оба JSON конфигурации формат записи информации, в котором бывший записывается Sublime Text конфигурации по умолчанию, пользователю запрещено редактировать, последний пуст по умолчанию, что позволяет пользователям изменять. Содержание Профили пользователей будут охватывать соответствующий контент по умолчанию, до тех пор, как модифицированный Enough Профиль пользователя.
Например, я теперь Пользовательская конфигурация выглядит следующим образом:
Открыть, закрыть, перейти к
Новая команда файлов + N
Команда Перейти + P, к документам, проецировать приглашение к методу (Гото ничего) команды + T Перейти к команде File + R, чтобы добраться до управления линией + G
Контроль + `Переключатель консоли
Команда + W закрывает текущие ярлыки файлов
Команда + K + B Переведите левый столбец
Прямо в файле, выберите выявить в боковой панели или Ctrl + Shift + \ открыть текущий файл находится на пути в левой колонке
Способ установки плагинов
Мы установили контроль пакета при нормальных обстоятельствах, Command + Shift + P В поле, который появляется, введите установку, проверьте Package Control: Install Package Просто введите режим плагина установки. Введите имя плагина, который вы хотите установить в поле поиска, а затем введите, будет установлен возврат. В процессе установки плагина будет один в нижнем левом углу возвышенного. = Встряхнуть вокруг.
Но после того, как я выберу установочный пакет, не имейте поле поиска и сообщите об ошибке:
Причиной ошибки состоит в том, что адрес интерфейса ST3 прочитанного списка плагина изменился, и Tianchao посетил этот адрес.
На данный момент вы можете установить различные плагины. В чем проблема?
"Use UTF-8 as the source file encoding."
Using the UTF-8 file encoding is pretty much a standard for most files.
Найти и заменить
Команда + опция + F Найти и заменить
In this post I’ll go over how I set up Sublime Text Editor for Ruby on Rails development.
Sublime Text Editor is a popular proprietary text editor that runs on Windows, Linux and Mac OS. It’s highly customizeable, with many user-developed plugins that tweak various parts of the interface.
The full program can be evaluated for free indefinitely. It is paid software, so in evaluation mode you’ll receive a prompt asking if you’d like to purchase a license after every few file saves ($80 USD as of September 2017).
Step 1: Download Sublime Text Editor 3.
Update (2017-09-17): As of September 2017, Sublime provides official repositories for apt, pacman, yum, dnf, and zypper, so Linux users can get updates through their package manager of choice after adding sublime-text to their source list as per their install instructions.
Step 2: Install Package Control Manager.
Step 3: Install any Sublime Text Editor plugins.
Once you have Package Control Manager installed, you can open “Preferences/Package Control” to access the package manager interface.
Enter “Install Package” to get a list of all available plugins.
I currently use the following plugins. Links are provided for interest only, you can install the plugins within Sublime Text Editor using the package manager.
Step 4: Add global key-bindings under “Preferences/Key Bindings - User”.
You can see “Preferences/Key Bindings - Default” for examples.
I like to set a key binding for reindenting files.
Step 5: Add global settings under “Preferences/Settings - User”.
Step 6: Add project-specific settings.
If this is a new project, you can create a project-specific settings file by going to “Project/Save Project As…” and saving a file as project_name.sublime-project.
For my current project I’m using 2-space indentation, so I have the following settings in my sublime-project file:
Note: It can be a good idea to check .sublime-project files into version control so everyone has the same settings, and ignore other Sublime config files.
Step 7: (Debian LXDE) Set up a keyboard shortcut for starting Sublime Text Editor.
This is strictly optional, but in Linux I like to have keybindings for starting terminals and development environments.
Using Debian LXDE, I added the following keybinding to ~/.config/openbox/lxde-rc.xml. Keybindings can be added within the
This keybinding starts Sublime Text Editor whenever the user types “Ctrl+Alt+s”. You can use any other key combination you like.
Final Ruby.sublime-settings file
I've listed the completed Ruby.sublime-settings file for easy copy-pasting. Enjoy.
The Ruby style guide has many more standards and best practices contained within it. Some of which we won't be able to configure via a simple settings file. Good thing we have the awesome gem Rubocop to tell us how to fix our code.
Установить контроль пакета
Управление пакетами - это инструмент управления плагином Sublime, который установлен, который может легко установить различные плагины.
Но у меня все еще есть ошибка после попытки снова попробовать, и я не знаю, почему: может быть, это проблема с Python, установленной на моем компьютере; но, возможно, сброс пакета не может быть доступен.
В конце концов я выбрал путь в автономном монтаже:Управление пакетами Оффлайн Пакет загрузки АдресНажмите Clone or download После нажатия Download ZIP 。
Упакуйте загруженный ZIP и переименуйте его как Package Control (Примечание: первые буквы двух слов должны быть заглавны)。
Открыть ST3, предпочтения - просматривайте пакеты, Package Control Папки копируются в этот каталог.
Перезапустите ST3, если предпочтения имеют два элемента для настроек пакета и управление пакетом, управление пакетом успешно.
Но после перезагрузки будут следующие советы: It appears you have Package Control installed as both a .sublime-package file and a directory inside of the Packages folder. Решение: Предпочтения - Обзор пакетов, в настоящее время вы войдете в каталог управления пакетами, щелкнув несколько файлов в верхнем левом углу нижней части, чтобы увидеть установленные пакеты пакетов под Sublime Text 3, удалите файлы под установленные пакеты , Пакет Control.sublime-package.
Sublime Suity Git Default Editor
воплощать в жизнь git config --global core.editor "subl -n -w" Я После выполнения этой команды вы можете открыть ~/.gitconfig Файл, чтобы увидеть ваши настройки.
Sublime Text 3 устанавливается и сконфигурирован как Ruby на редакторе Rails в среде Mac.
"Serve the public trust, protect the innocent, uphold the law." Ruby Proposed Standards
This section includes the cherry-picked settings that can be configured in your Ruby.sublime-settings file. These will help bring your coding environment one step closer to being a highly efficient and up to standards workflow.
Обычно используемые сочетания клавиш
Читайте также: