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
Use 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
.
Intentions
RubyMine’s intentions offer many different ways for generating and modifying code. A yellow lightbulb icon in the editor indicates that intentions are available.
Press 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.
Live Templates
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 tab
.
Here’s some of my favorite live templates:
def
– create an instance methoddefs
– create a class (singleton) methoddo
– create ado...end
blockdoo
– create ado |object| ...end
block that expects an argumentdest
– RSpecdescribe
a typedes
– RSpecdescribe
a methodit
– create an RSpec examplep
– access a Rails controller’sparams
objects
– access a Rails controller’ssession
object
Automate It
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.