When learning how to program, you were probably taught not to copy and paste code. Typing it out manually improved your understanding of its syntax and structure. However, after learning a particular concept, repeatedly typing it becomes boring and tedious. An IDE can help you automate this process by intelligently generating boilerplate code. In this post, we’ll take a look at code generation in RubyMine on OS X.
Generating Getters and Setters
If a class has instance variables, press
command + N in the editor to generate getters, setters, or both.
After selecting what type of method to generate, RubyMine will prompt you for the instance variable to generate it for.
Generating Overridden Methods
control + O to view a list of overridable methods.
Select a method from this dialog to generate a stub for it.
Generating Surrounding Code
Surround code with conditionals and other language constructs using
command + alt/option + T.
Remove surrounding code with
command + shift + delete.
RubyMine’s intentions offer many different ways for generating and modifying code. A yellow lightbulb icon in the editor indicates that intentions are available.
alt/option + enter to view the intention. Press
enter to execute it.
Intentions can even create classes.
Use intentions to modify code e.g., converting from Ruby 1.8 to 1.9 Hash syntax or converting a string from double to single quotes.
RubyMine’s live templates are commonly known as snippets in other editors. Press
command + J to view the list of available live templates.
Live templates are more commonly inserted by typing an abbreviation and then pressing
Here’s some of my favorite live templates:
def– create an instance method
defs– create a class (singleton) method
do– create a
doo– create a
do |object| ...endblock that expects an argument
it– create an RSpec example
p– access a Rails controller’s
s– access a Rails controller’s
Once you understand a particular concept, Ruby or Rails, as a programmer, your goal should be to automate it. If you’re beginning Ruby or Rails, then I would avoid code generation in order to better familiarize yourself with the language and framework. However, if you’re a veteran Rubyist, then I see nothing wrong with automating what you already know.
About the AuthorMore Content by Jared Carroll