Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Shopify’s Ruby Style Guide

License

NotificationsYou must be signed in to change notification settings

Shopify/ruby-style-guide

Repository files navigation

layouttitlepermalink
base
Ruby Style Guide
/

Ruby is the main language at Shopify. We are primarily a Ruby shop and we areprobably one of the largest out there. Ruby is the go-to language for new webprojects and scripting.

We expect all developers at Shopify to have at least a passing understanding ofRuby. It's a great language. It will make you a better developer no matter whatyou work in day to day. What follows is a loose coding style to follow whiledeveloping in Ruby.

This Style Guide is the result of over a decade of Ruby development at Shopify.Much of its content is based on Bozhidar Batsov'sRuby StyleGuide, adapted to Shopify bymanycontributors.

Adoption with RuboCop

We recommend usingRuboCop in your Rubyprojects to help you adopt this Style Guide. To know how to install and useRuboCop please refer toRuboCop's officialdocumentation.

We offer a default RuboCop configuration you can inherit from and be in syncwith this Style Guide. To use it, you can add this to yourGemfile:

gem"rubocop-shopify",require:false

And add to the top of your project's RuboCop configuration file:

inherit_gem:rubocop-shopify:rubocop.yml

AnyInclude orExclude configuration provided will be merged with RuboCop's defaults.

For more information about inheriting configuration from a gem please checkRuboCop'sdocumentation.

Table of Contents

General

  • Make all lines of your methods operate on the same level of abstraction.(Single Level of Abstraction Principle)

  • Code in a functional way. Avoid mutation (side effects) when you can.

  • Avoid defensive programming

    Overly defensive programming may safeguard against errors that will never be encountered, thus incurring run-time and maintenance costs.

  • Avoid mutating arguments.

  • Avoid monkeypatching.

  • Avoid long methods.

  • Avoid long parameter lists.

  • Avoid needless metaprogramming.

  • Preferpublic_send oversend so as not to circumventprivate/protectedvisibility.

  • Writeruby -w safe code.

  • Avoid more than three levels of block nesting.

Layout

  • UseUTF-8 as the source file encoding.

  • Use 2 space indent, no tabs.

  • Use Unix-style line endings.

  • Avoid using; to separate statements and expressions. Use oneexpression per line.

  • Use spaces around operators, after commas, colons and semicolons, around{and before}.

  • Avoid spaces after(,[ and before],).

  • Avoid space after the! operator.

  • Avoid space inside range literals.

  • Avoid space around method call operators.

    # badfoo.bar# goodfoo.bar
  • Avoid space in lambda literals.

    # bada=->(x,y){x +y}# gooda=->(x,y){x +y}
  • Indentwhen as deep as thecase line.

  • When assigning the result of a conditional expression to a variable, align itsbranches with the variable that receives the return value.

    # badresult=ifsome_cond# ...# ...calc_somethingelsecalc_something_elseend# goodresult=ifsome_cond# ...# ...calc_somethingelsecalc_something_elseend
  • When assigning the result of a begin block, align rescue/ensure/end with the start of the line

    # badhost=beginURI.parse(value).hostrescueURI::Errornilend# goodhost=beginURI.parse(value).hostrescueURI::Errornilend
  • Use empty lines between method definitions and also to break up methods intological paragraphs internally.

  • Use spaces around the= operator when assigning default values to methodparameters.

  • Avoid line continuation\ where not required.

  • Align the parameters of a method call, if they span more than one line, withone level of indentation relative to the start of the line with the methodcall.

    # starting point (line is too long)defsend_mail(source)Mailer.deliver(to:"bob@example.com",from:"us@example.com",subject:"Important message",body:source.text)end# bad (double indent)defsend_mail(source)Mailer.deliver(to:"bob@example.com",from:"us@example.com",subject:"Important message",body:source.text)end# gooddefsend_mail(source)Mailer.deliver(to:"bob@example.com",from:"us@example.com",subject:"Important message",body:source.text,)end
  • When chaining methods on multiple lines, indent successive calls by one levelof indentation.

    # bad (indented to the previous call)User.pluck(:name).sort(&:casecmp).chunk{ |n|n[0]}# goodUser.pluck(:name).sort(&:casecmp).chunk{ |n|n[0]}
  • Align the elements of array literals spanning multiple lines.

  • Limit lines to 120 characters.

  • Avoid trailing whitespace.

  • Avoid extra whitespace, except for alignment purposes.

  • End each file with a newline.

  • Avoid block comments:

    # bad=begincomment lineanother comment line=end# good# comment line# another comment line
  • Place the closing method call brace on the line after the last argument whenopening brace is on a separate line from the first argument.

    # badmethod(arg_1,arg_2)# goodmethod(arg_1,arg_2,)
  • Place each element/argument on a new line when wrapping a method call, hash, or arrayon multiple lines.

    # badmethod(arg_1,arg_2,arg_3)[value_1,value_2,value_3,]{key1:value_1,key2:value_2,key3:value_3,}# goodmethod(arg_1,arg_2,arg_3,)[value_1,value_2,value_3,]{key1:value_1,key2:value_2,key3:value_3,}# good (special cases)# Single argument method callmethod({foo:bar,})# Last argument, itself is multilineclassUserafter_save:method,if:->{do_some_checks}end# Single value arrayerrors=[{error_code:1234,error_message:"This is an error",}]
  • Separate magic comments from code and documentation with a blank line.

    # good# frozen_string_literal: true# Some documentation for PersonclassPerson# Some codeend# bad# frozen_string_literal: true# Some documentation for PersonclassPerson# Some codeend
  • Use empty lines around attribute accessor.

    # badclassFooattr_reader:foodeffoo# do something...endend# goodclassFooattr_reader:foodeffoo# do something...endend
  • Avoid empty lines around method, class, module, and block bodies.

    # badclassFoodeffoobegindo_somethingdosomethingendrescuesomethingendtrueendend# goodclassFoodeffoobegindo_somethingdosomethingendrescuesomethingendendend

Syntax

  • Use:: only to reference constants (this includes classes and modules) andconstructors (likeArray() orNokogiri::HTML()). Avoid:: forregular method invocation.

  • Avoid using:: for defining class and modules, or for inheritance, sinceconstant lookup will not search in parent classes/modules.

    # badmoduleAFOO="test"endclassA::BputsFOO# this will raise a NameError exceptionend# goodmoduleAFOO="test"classBputsFOOendend
  • Use def with parentheses when there are parameters. Omit the parentheses whenthe method doesn't accept any parameters.

  • Avoidfor.

  • Avoidthen.

  • Favour the ternary operator(?:) overif/then/else/end constructs.

    # badresult=ifsome_conditionthensomethingelsesomething_elseend# goodresult=some_condition ?something :something_else
  • Use one expression per branch in a ternary operator. This also means thatternary operators must not be nested. Prefer if/else constructs in thesecases.

  • Avoid multiline?: (the ternary operator); useif/unless instead.

  • Usewhen x then ... for one-line cases.

  • Use! instead ofnot.

  • Prefer&&/|| overand/or.

  • Favourunless overif for negative conditions.

  • Avoidunless withelse. Rewrite these with the positive case first.

  • Use parentheses around the arguments of method invocations. Omit parentheseswhen not providing arguments. Also omit parentheses when the invocation issingle-line and the method:

    • is a class method call with implicit receiver.
    • is called by syntactic sugar (e.g:1 + 1 calls the+ method,foo[bar]calls the[] method, etc).
    # badclassUserinclude(Bar)has_many(:posts)end# goodclassUserincludeBarhas_many:postsSomeClass.some_method(:foo)end
    • is one of the following methods:
      • require
      • require_relative
      • require_dependency
      • yield
      • raise
      • puts
  • Omit the outer braces around an implicit options hash.

  • Use the proc invocation shorthand when the invoked method is the onlyoperation of a block.

    # badnames.map{ |name|name.upcase}# goodnames.map(&:upcase)
  • Prefer{...} overdo...end for single-line blocks.

  • Preferdo..end over{...} for multi-line blocks.

  • Omitreturn where possible.

  • Omitself where possible.

    # badself.my_method# goodmy_method# also goodattr_writer:namedefmy_methodself.name="Rafael"# `self` is needed to reference the attribute writer.end
  • Wrap assignment in parentheses when using its return value in a conditionalstatement.

    if(value=/foo/.match(string))
  • Use||= to initialize variables only if they're not already initialized.

  • Avoid using||= to initialize boolean variables.

    # bad - would set enabled to true even if it was false@enabled ||=true# good@enabled=trueif@enabled.nil?# also valid - defined? workaround@enabled=trueunlessdefined?(@enabled)
  • Avoid spaces between a method name and the opening parenthesis.

  • Prefer the lambda literal syntax overlambda.

    # badl=lambda{ |a,b|a +b}l.call(1,2)l=lambdado |a,b|tmp=a *7tmp *b /50end# goodl=->(a,b){a +b}l.call(1,2)l=->(a,b)dotmp=a *7tmp *b /50end
  • Preferproc overProc.new.

  • Prefix unused block parameters with_. It's also acceptable to use just_.

  • Prefer a guard clause when you can assert invalid data. A guard clause is aconditional statement at the top of a function that bails out as soon as itcan.

    # baddefcompute_thing(thing)ifthing[:foo]update_with_bar(thing)ifthing[:foo][:bar]partial_compute(thing)elsere_compute(thing)endendend# gooddefcompute_thing(thing)returnunlessthing[:foo]update_with_bar(thing[:foo])returnre_compute(thing)unlessthing[:foo][:bar]partial_compute(thing)end
  • Prefer keyword arguments over options hash.

  • Prefermap overcollect,find overdetect,select overfind_all,size overlength.

  • PreferTime overDateTime.

  • PreferTime.iso8601(foo) instead ofTime.parse(foo) when expecting ISO8601formatted time strings like"2018-03-20T11:16:39-04:00".

  • Avoid returning from abegin block in assignment contexts. If you returnfrom a method inside abegin block, the return will prevent the assignmentfrom taking place, potentially causing confusing memoization bugs.

    # baddeffoo@foo ||=beginreturn1ifflag?2endend# gooddeffoo@foo ||=beginifflag?1else2endendend

Naming

  • Usesnake_case for symbols, methods, and variables.

  • UseCamelCase for classes and modules, but keep acronyms like HTTP, RFC, XMLuppercase.

  • Usesnake_case for naming files and directories, e.g.hello_world.rb.

  • Define a single class or module per source file. Name the file name as theclass or module, but replacingCamelCase withsnake_case.

  • UseSCREAMING_SNAKE_CASE for other constants.

  • When using inject with short blocks, name the arguments according to what isbeing injected, e.g.|hash, e| (mnemonic: hash, element)

  • When defining binary operators, name the parameterother(<< and[] areexceptions to the rule, since their semantics are different).

  • Name predicate methods with a?. Predicate methods are methods that return aboolean value.

  • Avoid ending method names with a? if they don't return a boolean.

  • Avoid prefixing method names withis_.

    # baddefis_empty?end# gooddefempty?end
  • Avoid starting method names withget_.

  • Avoid ending method names with! when there is no equivalent method withoutthe bang. Bangs are to mark a more dangerous version of a method, e.g.savereturns a boolean in ActiveRecord, whereassave! will throw an exception onfailure.

  • Avoid magic numbers. Use a constant and give it a meaningful name.

  • Avoid nomenclature that has (or could be interpreted to have) discriminatoryorigins.

Comments

  • Include relevant context in comments, as readers might be missing it.

  • Keep comments in sync with code.

  • Write comments using proper capitalization and punctuation.

  • Avoid superfluous comments. Focus onwhy the code is the way it is ifthis is not obvious, nothow the code works.

Classes and Modules

  • Prefer modules to classes with only class methods. Classes should be used onlywhen it makes sense to create instances out of them.

  • Preferextend self overmodule_function.

    # badmoduleSomeModulemodule_functiondefsome_methodenddefsome_other_methodendend# goodmoduleSomeModuleextendselfdefsome_methodenddefsome_other_methodendend
  • Use aclass << self block overdef self. when defining class methods, andgroup them together within a single block.

    # badclassSomeClassdefself.method1enddefmethod2endprivatedefmethod3enddefself.method4# this is actually not privateendend# goodclassSomeClassclass <<selfdefmethod1endprivatedefmethod4endenddefmethod2endprivatedefmethod3endend
  • Respect theLiskov Substitution Principlewhen designing class hierarchies.

  • Useattr_accessor,attr_reader, andattr_writer to define trivialaccessors and mutators.

    # badclassPersondefinitialize(first_name,last_name)@first_name=first_name@last_name=last_nameenddeffirst_name@first_nameenddeflast_name@last_nameendend# goodclassPersonattr_reader:first_name,:last_namedefinitialize(first_name,last_name)@first_name=first_name@last_name=last_nameendend
  • Preferattr_reader andattr_accessor overattr.

  • Avoid class (@@) variables.

  • Indent thepublic,protected, andprivate methods as much as the methoddefinitions they apply to. Leave one blank line above the visibility modifierand one blank line below it.

    classSomeClassdefpublic_method# ...endprivatedefprivate_method# ...enddefanother_private_method# ...endend
  • Preferalias_method overalias.

Exceptions

  • Signal exceptions using theraise method.

  • OmitRuntimeError in the two argument version ofraise.

    # badraiseRuntimeError,"message"# good - signals a RuntimeError by defaultraise"message"
  • Prefer supplying an exception class and a message as two separate arguments toraise instead of an exception instance.

    # badraiseSomeException.new("message")# Note that there is no way to do `raise SomeException.new("message"), backtrace`.# goodraiseSomeException,"message"# Consistent with `raise SomeException, "message", backtrace`.
  • Avoid returning from anensure block. If you explicitly return from a methodinside anensure block, the return will take precedence over any exceptionbeing raised, and the method will return as if no exception had been raised atall. In effect, the exception will be silently thrown away.

    # baddeffooraiseensurereturn"very bad idea"end
  • Use implicit begin blocks where possible.

    # baddeffoobegin# main logic goes hererescue# failure handling goes hereendend# gooddeffoo# main logic goes hererescue# failure handling goes hereend
  • Avoid emptyrescue statements.

    # badbegin# an exception occurs hererescueSomeError# the rescue clause does absolutely nothingend# bad - `rescue nil` swallows all errors, including syntax errors, and# makes them hard to track down.do_somethingrescuenil
  • Avoidrescue in its modifier form.

    # bad - this catches exceptions of StandardError class and its descendant# classes.read_filerescuehandle_error($!)# good - this catches only the exceptions of Errno::ENOENT class and its# descendant classes.deffooread_filerescueErrno::ENOENT=>errorhandle_error(error)end
  • Avoid rescuing theException class.

    # badbegin# calls to exit and kill signals will be caught (except kill -9)exitrescueExceptionputs"you didn't really want to exit, right?"# exception handlingend# goodbegin# a blind rescue rescues from StandardError, not Exception.rescue=>error# exception handlingend
  • Prefer exceptions from the standard library over introducing new exceptionclasses.

  • Use meaningful names for exception variables.

    # badbegin# an exception occurs hererescue=>e# exception handlingend# goodbegin# an exception occurs hererescue=>error# exception handlingend

Collections

  • Use literal array and hash creation notation unless you need to passparameters to their constructors.

    # badarr=Array.newhash=Hash.new# goodarr=[]hash={}
  • Prefer the literal array syntax over%w or%i.

    # badSTATES=%w(draftopenclosed)# goodSTATES=["draft","open","closed"]
  • Append a trailing comma in multi-line collection literals.

    # bad{foo::bar,baz::toto}# good{foo::bar,baz::toto,}
  • When accessing the first or last element from an array, preferfirst orlast over[0] or[-1].

  • Avoid mutable objects as hash keys.

  • Use shorthand hash literal syntax when all keys are symbols.

    # bad{:a=>1,:b=>2}# good{a:1,b:2}
  • Prefer hash rockets syntax over shorthand syntax when not all keys aresymbols.

    # bad{a:1,"b"=>2}# good{:a=>1,"b"=>2}
  • PreferHash#key? overHash#has_key?.

  • PreferHash#value? overHash#has_value?.

  • UseHash#fetch when dealing with hash keys that should be present.

    heroes={batman:"Bruce Wayne",superman:"Clark Kent"}# bad - if we make a mistake we might not spot it right awayheroes[:batman]# => "Bruce Wayne"heroes[:supermann]# => nil# good - fetch raises a KeyError making the problem obviousheroes.fetch(:supermann)
  • Introduce default values for hash keys viaHash#fetch as opposed to usingcustom logic.

    batman={name:"Bruce Wayne",is_evil:false}# bad - if we just use || operator with falsy value we won't get the expected resultbatman[:is_evil] ||true# => true# good - fetch work correctly with falsy valuesbatman.fetch(:is_evil,true)# => false
  • Place] and} on the line after the last element when openingbrace is on a separate line from the first element.

    # bad[1,2]{a:1,b:2}# good[1,2,]{a:1,b:2,}

Strings

  • Prefer string interpolation and string formatting instead of stringconcatenation:

    # bademail_with_name=user.name +" <" +user.email +">"# goodemail_with_name="#{user.name} <#{user.email}>"# goodemail_with_name=format("%s <%s>",user.name,user.email)
  • Avoid padded-spacing inside braces in interpolated expressions.

    # bad"From:#{user.first_name},#{user.last_name}"# good"From:#{user.first_name},#{user.last_name}"
  • Use double-quoted strings.

    # bad'Just some text''No special chars or interpolation'# good"Just some text""No special chars or interpolation""Every string in#{project} uses double_quotes"
  • Avoid the character literal syntax?x.

  • Use{} around instance and global variables being interpolated into astring.

    classPersonattr_reader:first_name,:last_namedefinitialize(first_name,last_name)@first_name=first_name@last_name=last_nameend# bad - valid, but awkwarddefto_s"#@first_name #@last_name"end# gooddefto_s"#{@first_name}#{@last_name}"endend$global=0# badputs"$global = #$global"# fine, but don't use globalsputs"$global =#{$global}"
  • AvoidObject#to_s on interpolated objects.

    # badmessage="This is the#{result.to_s}."# good - `result.to_s` is called implicitly.message="This is the#{result}."
  • AvoidString#gsub in scenarios in which you can use a faster morespecialized alternative.

    url="http://example.com"str="lisp-case-rules"# badurl.gsub("http://","https://")str.gsub("-","_")str.gsub(/[aeiou]/,"")# goodurl.sub("http://","https://")str.tr("-","_")str.delete("aeiou")
  • When using heredocs for multi-line strings keep in mind the fact that theypreserve leading whitespace. It's a good practice to employ some margin basedon which to trim the excessive whitespace.

    code=<<-END.gsub(/^\s+\|/,"")  |def test  |  some_method  |  other_method  |endEND# => "def test\n  some_method\n  other_method\nend\n"# In Rails you can use `#strip_heredoc` to achieve the same resultcode=<<-END.strip_heredoc  def test    some_method    other_method  endEND# => "def test\n  some_method\n  other_method\nend\n"
  • In Ruby 2.3, prefer"squigglyheredoc" syntax, which has the samesemantics asstrip_heredoc from Rails:

    code=<<~END  def test    some_method    other_method  endEND# => "def test\n  some_method\n  other_method\nend\n"
  • Indent heredoc contents and closing according to its opening.

    # badclassFoodefbar<<~SQL      'Hi'  SQLendend# goodclassFoodefbar<<~SQL      'Hi'    SQLendend# bad# heredoc contents is before closing heredoc.fooarg,<<~EOS  Hi    EOS# goodfooarg,<<~EOS  HiEOS# goodfooarg,<<~EOS    Hi  EOS

Regular Expressions

  • Prefer plain text search over regular expressions in strings.

    string["text"]
  • Use non-capturing groups when you don't use the captured result.

    # bad/(first|second)/# good/(?:first|second)/
  • PreferRegexp#match over Perl-legacy variables to capture group matches.

    # bad/(regexp)/ =~stringprocess $1# good/(regexp)/.match(string)[1]
  • Prefer named groups over numbered groups.

    # bad/(regexp)/ =~string...processRegexp.last_match(1)# good/(?<meaningful_var>regexp)/ =~string...processmeaningful_var
  • Prefer\A and\z over^ and$ when matching strings from start to end.

    string="some injection\nusername"string[/^username$/]# `^` and `$` matches start and end of lines.string[/\Ausername\z/]# `\A` and `\z` matches start and end of strings.

Percent Literals

  • Use%() for single-line strings which require both interpolation andembedded double-quotes. For multi-line strings, prefer heredocs.

  • Avoid%q unless you have a string with both' and" in it. Regularstring literals are more readable and should be preferred unless a lot ofcharacters would have to be escaped in them.

  • Use%r only for regular expressions matching at least one/ character.

    # bad%r{\s+}# good%r{^/(.*)$}%r{^/blog/2011/(.*)$}
  • Avoid the use of%s. Use:"some string" to create a symbol with spaces init.

  • Prefer() as delimiters for all% literals, except, as often occurs inregular expressions, when parentheses appear inside the literal. Use the firstof(),{},[],<> which does not appear inside the literal.

Testing

  • Treat test code like any other code you write. This means: keep readability,maintainability, complexity, etc. in mind.

  • Prefer Minitest as the test framework.

  • Limit each test case to cover a single aspect of your code.

  • Organize the setup, action, and assertion sections of the test case intoparagraphs separated by empty lines.

    test"sending a password reset email clears the password hash and set a reset token"douser=User.create!(email:"bob@example.com")user.mark_as_verifieduser.send_password_reset_emailassert_niluser.password_hashrefute_niluser.reset_tokenend
  • Split complex test cases into multiple simpler tests that test functionalityin isolation.

  • Prefer usingtest "foo"-style syntax to define test cases overdef test_foo.

  • Prefer using assertion methods that will yield a more descriptive errormessage.

    # badassertuser.valid?assertuser.name =="tobi"# goodassert_predicateuser,:valid?assert_equal"tobi",user.name
  • Avoid usingassert_nothing_raised. Use a positive assertion instead.

  • Prefer using assertions over expectations. Expectations lead to more brittletests, especially in combination with singleton objects.

    # badStatsD.expects(:increment).with("metric")do_something# goodassert_statsd_increment("metric")dodo_somethingend

[8]ページ先頭

©2009-2025 Movatter.jp