A guide for programming in style.
Use Hound to automatically review your code and comment on GitHub pull requests for violations of the Ruby portions of this style guide.
- Avoid merge commits by using a rebase workflow.
- Prefix feature branch names with your initials.
- Squash multiple trivial commits into a single commit.
- Write a good commit message.
- Avoid inline comments.
- Break long lines after 80 characters.
- Delete trailing whitespace.
- Don't include spaces after
(,[or before],). - Don't misspell.
- Don't vertically align tokens on consecutive lines.
- If you break up an argument list, keep the arguments on their own lines and closing parenthesis on its own line.
- If you break up a hash, keep the elements on their own lines and closing curly brace on its own line.
- Indent continued lines two spaces.
- Indent private methods equal to public methods.
- If you break up a chain of method invocations, keep each method invocation on
its own line. Place the
.at the end of each line, except the last. Example. - Use 2 space indentation (no tabs).
- Use an empty line between methods.
- Use empty lines around multi-line blocks.
- Use spaces around operators, except for unary operators, such as
!. - Use spaces after commas, after colons and semicolons, around
{and before}. - Use Unix-style line endings (
\n). - Use uppercase for SQL key words and lowercase for SQL identifiers.
- Avoid abbreviations.
- Avoid object types in names (
user_array,email_methodCalculatorClass,ReportModule). - Prefer naming classes after domain concepts rather than patterns they
implement (e.g.
GuestvsNullUser,CachedRequestvsRequestDecorator). - Name the enumeration parameter the singular of the collection.
- Name variables created by a factory after the factory (
user_factorycreatesuser). - Name variables, methods, and classes to reveal intent.
- Treat acronyms as words in names (
XmlHttpRequestnotXMLHTTPRequest), even if the acronym is the entire name (class Htmlnotclass HTML). - Suffix variables holding a factory with
_factory(user_factory).
- Order methods so that caller methods are earlier in the file than the methods they call.
- Order methods so that methods are as close as possible to other methods they call.
- Use the Scss syntax.
- Use hyphens when naming mixins, extends, classes, functions & variables:
span-columnsnotspan_columnsorspanColumns. - Use space between property and value:
width: 20pxnotwidth:20px. - Use a blank line above selector that has styles.
- Prefer hex color codes
#000. - Use
//for comment blocks not/* */. - Use a space between selector and
{. - Use double quotation marks.
- Use only lowercase, including colors.
- Don't add a unit specification after
0values, unless required by a mixin. - Use a leading zero in decimal numbers:
0.5not.5 - Use space around operands:
$variable * 1.5, not$variable*1.5 - Avoid in-line operations in shorthand declarations (Ex.
padding: $variable * 1.5 variable * 2) - Use parentheses around individual operations in shorthand declarations:
padding: ($variable * 1.5) ($variable * 2)
- Use alphabetical order for declarations.
- Place @extends and @includes at the top of your declaration list.
- Place media queries directly after the declaration list.
- Place concatenated selectors second.
- Place pseudo states and elements third.
- Place nested selectors last.
- Don't use ID's for style.
- Use meaningful names:
$visual-grid-colornot$coloror$vslgrd-clr. - Use ID and class names that are as short as possible but as long as necessary.
- Avoid using the direct descendant selector
>. - Avoid nesting more than 4 selectors deep.
- Don't nest more than 6 selectors deep.
- Use HTML tags on vague classes that need a qualifier like
header.applicationnot.main. - Avoid using the HTML tag in the class name:
section.newsnotsection.news-section. - Avoid using HTML tags on classes for generic markup
<div>,<span>:.widgetsnotdiv.widgets. - Avoid using HTML tags on classes with specific class names like
.featured-articles. - Avoid using comma delimited selectors.
- Avoid nesting within a media query.
- Use Bourbon for a Sass Library.
- Use Neat for a grid framework.
- Use Bitters / Base folder for style on HTML tags, global variables, global extends and global mixins.
- Use Normalize as a browser reset.
- Use HTML structure for ordering of selectors. Don't just put styles at the bottom of the Sass file.
- Prefer the same file structure that is found in app/views.
- Avoid having files longer than 100 lines.
- Avoid conditional modifiers (lines that end with conditionals).
- Avoid backticks.
- Initialize arrays using
[]. - Initialize empty objects and hashes using
{}. - Prefer
==and!=toisandisnt - Prefer
||and&&toorandand - Prefer
!overnot - Prefer
@overthisfor referencing instance properties. - Prefer double quotes.
- Use hyphen-separated filenames, such as
coffee-script.coffee. - Use
PascalCasefor classes,lowerCamelCasefor variables and functions,SCREAMING_SNAKE_CASEfor constants,_single_leading_underscorefor private variables and functions. - Use zero spaces before and one space after the colon in a colon assignment (i.e. classes, objects).
- Organize all objects in one
window.Appnamespace. - Name collections the plural version of the model.
- Name models without a suffix.
- Name the router
App.Router. - Name views with a
Viewsuffix.
- Don't put a space between the opening handlebars braces and the variable.
- Avoid conditional modifiers (lines that end with conditionals).
- Avoid multiple assignments per line (
one, two = 1, 2). - Avoid organizational comments (
# Validations). - Avoid ternary operators (
boolean ? true : false). Use multi-lineifinstead to emphasize code branches. - Avoid explicit return statements.
- Avoid using semicolons.
- Avoid bang (!) method names. Prefer descriptive names.
- Don't use
selfexplicitly anywhere except class methods (def self.method) and assignments (self.attribute =). - Prefer
detectoverfind. - Prefer
injectoverreduce. - Prefer
mapovercollect. - Prefer
selectoverfind_all. - Prefer double quotes for strings.
- Prefer
&&and||overandandor. - Prefer
!overnot. - Prefer
&:method_nameto{ |item| item.method_name }for simple method calls. - Use
_for unused block parameters. - Use
%{}for single-line strings needing interpolation and double-quotes. - Use
{...}for single-line blocks. Usedo..endfor multi-line blocks. - Use
?suffix for predicate methods. - Use
CamelCasefor classes and modules,snake_casefor variables and methods,SCREAMING_SNAKE_CASEfor constants. - Use
def self.method, notdef Class.methodorclass << self. - Use
defwith parentheses when there are arguments. - Don't use spaces after required keyword arguments. Example
- Use
each, notfor, for iteration. - Use a trailing comma after each item in a multi-line list, including the last item. Example
- Use heredocs for multi-line strings.
- Prefer
protectedoverprivatefor non-publicattr_readers,attr_writers, andattr_accessors.
- When wrapping long lines, keep the method name on the same line as the ERb interpolation operator and keep each method argument on its own line.
- Prefer double quotes for attributes.
- Prefer double quotes for attributes.
- Avoid
memberandcollectionroutes. - Use private instead of protected when defining controller methods.
- Name date columns with
_onsuffixes. - Name datetime columns with
_atsuffixes. - Name initializers for their gem name.
- Order ActiveRecord associations alphabetically by attribute name.
- Order ActiveRecord validations alphabetically by attribute name.
- Order ActiveRecord associations above ActiveRecord validations.
- Order controller contents: filters, public methods, private methods.
- Order i18n translations alphabetically by key name.
- Order model contents: constants, macros, public methods, private methods.
- Put application-wide partials in the
app/views/applicationdirectory. - Use
def self.method, not thescope :methodDSL. - Use the default
render 'partial'syntax overrender partial: 'partial'. - Use
link_tofor GET requests, andbutton_tofor other HTTP verbs.
- Set an empty string as the default constraint for non-required string and text fields. Example.
- List timestamps first when creating a new table. Example.
- Avoid the
:exceptoption in routes. - Order resourceful routes alphabetically by name.
- Use the
:onlyoption to explicitly state exposed routes.
- Define a
PRIORITYconstant at the top of delayed job classes. - Define two public methods:
self.enqueueandperform. - Put delayed job classes in
app/jobs.
- Use the user's name in the
Fromheader and email in theReply-Towhen delivering email on behalf of the app's users.
- Avoid the
privatekeyword in specs. - Avoid checking boolean equality directly. Instead, write predicate methods and use appropriate matchers. Example.
- Prefer
eqto==in RSpec. - Separate setup, exercise, verification, and teardown phases with newlines.
- Use RSpec's
expectsyntax. - Use RSpec's
allowsyntax for method stubs. - Use
shouldshorthand for one-liners with an implicit subject. - Use
not_toinstead ofto_notin RSpec expectations. - Prefer the
have_cssmatcher to thehave_selectormatcher in Capybara assertions.
- Avoid scenario titles that add no information, such as "successfully."
- Avoid scenario titles that repeat the feature title.
- Place helper methods for feature specs directly in a top-level
Featuresmodule. - Use Capybara's
feature/scenarioDSL. - Use names like
ROLE_ACTION_spec.rb, such asuser_changes_password_spec.rb, for feature spec file names. - Use only one
featureblock per feature spec file. - Use scenario titles that describe the success and failure paths.
- Use spec/features directory to store feature specs.
- Use spec/support/features for support code related to feature specs.
- Order
factories.rbcontents: sequences, traits, factory definitions. - Order factory attributes: implicit attributes, explicit attributes, child factory definitions. Each section's attributes are alphabetical.
- Order factory definitions alphabetically by factory name.
- Use one factories.rb file per project.
- Don't prefix
itblock descriptions withshould. Use Imperative mood instead. - Put one-liner specs at the beginning of the outer
describeblocks. - Use
.methodto describe class methods and#methodto describe instance methods. - Use
contextto describe testing preconditions. - Use
describe '#method_name'to group tests by method-under-test - Use a single, top-level
describe ClassNameblock. - Order validation, association, and method tests in the same order that they appear in the class.
- Place
#imports into the prefix header (ProjectName-Prefix.pch) only if used in many files. - Place
.xibfiles underResources/Nibsand their associated view files inClasses/Views. - Order
#importstatements alphabetically. - Order
@classdirectives alphabetically. - Order
@propertymodifiers: memory management, atomicity, writability. - Leave out
@propertymodifiers unless needed,nonatomicis the only one needed in most cases except connecting views with IB in which caseweakmay also be needed. - Prefer
@classto#importwhen referring to external classes in a public@interface. - Prefer
@propertyto declaring instance variables. - Prefix class names with a 2 or 3 letter project acronym.
- Prefix string constants being used as keys with 'k'.
- Remove
#importstatements forFoundationandUIKitin new project templates. - Separate methods by function using
#pragma mark - <Section Name> - Separate sections into subsections using
#pragma mark <Subsection Name> - Use
@[arrayObject],@{@"key" : value},@(YES or NO), and@5.0literals. - Use
@interface ClassName ()to declare private properties. - Use
lowerCamelCasefor method names. - Use
NSAssertin methods that require the presence of certain arguments. - Write methods using the happy path. Indent the exceptional cases. Keep the optimal case in the left-most column.
- Prefer
enumerateObjectsUsingBlock:when looping through arrays. - Always use braces with control and loop blocks unless it can easily fit on one line.
- Place opening brace for control and loop blocks on same line.
- Prefer
NSInteger,CGFloat, and similar macros overint,float, and other base types. - Prefer Auto Layout for view layouts and constraints.
- Keep up with the Objective-C style guide above. Will highlight differences here.
- Use
letwhenever possible to make immutable variables - Name all parameters in functions and enum cases
- Use trailing closures
- Let the compiler infer the type whenever possible
- Follow PEP 8.
- Break long lines on
|,&&, or||and indent the continuations. - Don't add an extension to executable shell scripts.
- Don't put a line break before
thenordo, useif ...; thenandwhile ...; do. - Use
for x; do, notfor x in "$@"; do. - Use
snake_casefor variable names andALLCAPSfor environment variables. - Use single quotes for strings that don't contain escapes or variables.
- Use two-space indentation.
- Break long expressions before operators or keywords.
- Break long type signatures between arguments.
- Order imports in three sections, separating each by a blank line: standard libraries, third-party libraries, application modules. Within each section, alphabetize the imports and place qualified imports last.
- Use comma-first style exports, records, and lists.
- Use four-space indentation except the
wherekeyword which is indented two spaces. Example.
- Properties of views should be alphabetized, with the exception of
id,layout_width, andlayout_heightwhich should be placed first in that order.