Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

From Developer to Rails Developer, and Then Some

Tags: rails ruby code

It isn’t until I’m pair-programming with someone who is new to Ruby on Railsthat I remember the pain. I have so much weird muscle memory for Ruby and Railsand all of the tools that come along with Ruby and Rails. I take it all forgranted now; I’m an experienced Rails developer.You may have read about “the magic” of Rails. You may have even experienced it.But did you experience it à la carte? In order to “learn Rails” you must alsolearn, in many cases, Factory Bot, RSpec, YARD, Active Job, and Capybara. Youmay need to learn how Rack middleware works. You may need to write some YAML, orread something called a “VCR cassette” that outputs many large YAML files thatare “fun” to “read”. You may even need to learn your coworkers’s preferred,weird ways of writing Ruby (a very expressive language) that you just haven’tencountered yet. This all can be overwhelming.So, as an experienced Rails developer, I take for granted how easily I canfigure out how to do stuff. And how I can figure out how to do stuff if I don’tknow how to do. I take for granted that, when you’re new, you haven’tlearned where to look yet. None of this, by the way, is unique to the Ruby andRails ecosystems. Maybe you’ve gone through this “learning how to learn” processa few times already. Maybe you like it now.Whether you’re a junior developer or an experienced developer who is just new toRuby, the road from feeling completely lost to feeling able to move forwardmay be long. My aim in this post is to give you a small jump-start. To point youin the direction of what you need to learn and the resources that can helpyou learn it. So you, too, can take your past self for granted and leave thatcompletely lost feeling behind.Because my employer, Super Good, primarily works on Ruby on Rails applicationsthat use the Solidus ecommerce framework, some parts ofthis article point to stuff I do as a Solidus developer, and stuff I’ve learnedbecause I’m a Solidus developer. But if you don’t care about Solidus, don’t letthat sour you on this blog post. At the end of the day, Solidus is just anotherRails engine. As a Ruby developer, and a Rails developer, youinevitably will need to locate and understand source code that comes fromexternal dependencies. I hope you find that I’ve written this guide in a waythat equips you with the knowledge you need regardless of which gems are listedin your Gemfile.Before we get deep into things, I want to provide you with my opinionated,high-level checklist. Take it or leave it. It will take you more than a day,maybe more than a month, to confidently check off all these items, depending onyour starting point and your end goals. After many years using Ruby and Rails,I’ve identified each of these items as things that really helped me level upand feel more productive at work:These things build on one another, but not in a strictly linear way. You mayhave to go back and relearn stuff (Module#prepend versus Module#include?) asyou move forward. That said, read on if you want to know what each of theseitems really entails.Skip to the end if you just want my recommended readinglist—formatted as a three-weeklearning plan.If you’ve made it this far, I will assume that you have previously learnedanother programming language or are programming language-curious. If you’reunsure how to describe the difference between true and "true", thisblog post is not for you. And I’d recommend you go read “How to Pick aProgramming Language to Learn” instead. Ruby wouldbe a great first programming language to learn. With that said, my followingrecommendations will be more useful to someone who already sort of knows howprogramming languages work.If you’re looking to learn Ruby, I’d start at Ruby’s official website, which isthe home of two great articles: “Ruby in Twenty Minutes” and“Ruby from Other Languages”. One or both of thosearticles may be useful in your path to becoming fluent in Ruby.But the things that I found the most valuable early on in my Ruby journey wasthe the Edgecase Ruby Koans. Going through each ofthese tests, from start to finish, is an engaging, interactive way to getfamiliar with how to read and write Ruby. The Ruby Koans are so helpful, infact, that I recommend that you do them all twice: once when you’re juststarting, and once after six months or a year of writing Ruby somewhatregularly.I also want to highlight some text on the Ruby Koans homepage:Testing is not just something we pay lip service to, but something we live. Itis essential in your quest to learn and do great things in the language.I can’t speak for all Rubyists, but in relation to my own Ruby journey: this istrue.“Learning Ruby,” never stops, but it may take you a day or two before you go onto next item in the checklist. It’s okay if you don’t fully get Ruby, orunderstand everything the Koans have taught you. But in any case: good luck.Now that you can read and write Ruby, spend some time reading theEnumerable andArray core librarydocumentation. As a Rails developer, you will deal with arrays a lot. And aninstance of an Array not only has all of the standard array methods availableon it, but also all of the Enumerable methods, since an array is a type ofEnumerable:While you read through this documentation, I recommend keeping an open Rubyconsole nearby so you can try each method out. In my experience, manipulatingdead-simple objects is a quick way to test assumptions:By default, when you install Ruby, you can run irb to get into an interactiveRuby console. But I usually recommend installing Pryto take advantage of its advanced features. (LaterI will recommend Pry as a great debugger for other reasons, too, but let’sleave that until later.)As you read and write more Ruby, you will notice that inheritance comes up alot:And in many ways:Even if you don’t know Ruby yet, you probably have some idea of what’s going onin the above code snippets. But as you get deeper into real application andlibrary code, you may need to know what makes including a module on a Ruby classdifferent from prepending or extending a module on a class. There are many greatblog posts about this, so I won’t go into any more detail here. Just keep thisin mind as you move forward on your Ruby journey.In the above snippets, we covered Module#include, and the super keyword.Module#prepend and #extend will will be in the same wheelhouse, butModule#class_eval is a bit different. If you will be working on a legacyapplication (and, especially, a legacy Solidus application), you may encounterModule#class_eval as well—so be sure to check that out, too, if that’s whereyou’re coming from.Now that you have some Ruby foundations, you can see what Rails offers you as adeveloper. If you’re feeling adventurous, you could even jump into Rails’ssource code (maybe start with the activesupport gem) and make some sense of it.The Rails Guides can give you a better idea of what Rails is than I can. So Isuggest you start with their “Getting Started withRails” article. It may take you a full day tomeaningfully go through this article, but I think it’s worth the time. As aRails developer, you’ll need to understand what models are, how controllers androutes work together, how views work, and how all of these layers connect to oneanother. As you go through this Rails guide article:I recommend following along with a terminal open as you go. Run rails newfor yourself as you’re reading about it. Generate a database migration. Generatea new model. See what it feels like to create and run a fresh Rails application.With some Rails basics in hand, you can start work on your real Railsapplication. You may also just want to source-dive into some open sourceRails applications to see what real, in-the-wild feature code can look like.Check out the Mastodon git repository or the Discoursegit repository, for example.While you’re checking out a Rails application codebase, don’t forget to examineits test suite. Every Rails app is different, and when it comes to tests someRails apps use Ruby’s built-in test framework,Minitest and others useRSpec. There are many other Ruby testing tools that youmay or may not encounter. Sometimes when you’re reading RSpec tests(colloquially known as “specs”) withFactoryBot factories sprinkled in,you may not even feel like you’re reading Ruby code anymore.No matter what testing toolkits you or your colleagues use, you will want testsfor each layer of the Rails application: the model layer, the controller layer,the view layer—and probably some other layers, depending on the app inquestion. Fortunately, Rails comes with testing mechanisms to make this jobeasier.I recommend reading the Rails Guides’s “Testing RailsApplication” next. That guide istailor-made for Rails applications using Minitest. But in my experience, manyRails applications use RSpec (and rspec-rails) instead of Minitest. Putreading the RSpec documentation in your tentative to-do list.If you’re new to Ruby, learning Ruby and Rails and RSpec and all of theother testing tools being used within your RSpec tests, all at the same time,will be painful. If you look at Mastodon’s rails_helperfile, which defines some functionality that getsincluded before many of the application’s test files are run, you will encounterreferences to a bunch of stuff that you can’t make sense of without reading alot more documentation, and a lot more source code.As with all toolboxes, you’ll come to recognize the tools that Rails developersreach for most often. You’ll see something like this:And you’ll just know: “Oh, the person who wrote this is using theFactoryBot #create method to create an blog post object. If I need to knowwhat class that object is, I should go find where the :blog_post factory isdefined. And blog posts have an association, #author, which has its own:author factory. All of this is happening before the test runs.”But, yeah, you won’t know any of that at first.Even worse: maybe the factory isn’t defined in your application, and it’s beingincluded from some third-party library in your Gemfile. How do you locate stuffwhen you don’t even understand what it is to begin with? We’ll hopefully answerthat question in the next section, about getting comfortable with your debuggingtools.In this post I haven’t even begun to cover things like RSpec’s mocking utilitiesor tools like VCR which can totally change how andwhat you test. For a while, you can get away with just knowing that these toolsexist, and recognizing them when you see them in passing. But eventually, you’llneed to sit down with each of these tools and their READMEs individually.If you just finished reading the previous section and feel overwhelmed by theamount of things you haven’t learned yet, I bring good news: your debuggingtools not only help you resolve bugs in software, they help you find solidground when you don’t know where to look next. In the end, you need to debug andfind your footing in the way that works for your brain (and your text editor). Ijust hope that you can:When I work on Rails apps, this boils down to using Pry and bundle open, forthe most part.Earlier I mentioned Pry, an alternative interactiveshell and REPL (read-evaluate-print loop) to the Ruby’s built-in one, IRB. IRBis really nice, especially on newer Rubies like 3.1 and 3.2. But Pry comes withsome tools that IRB doesn’t come with. And, without any configuration, sometimesseems to just format things the way my brain works a little better than IRBdoes. (But your mileage may vary.)Pry’s killer feature, in my opinion, is show-source—or $, for short:In a few seconds, we’ve just located the place in the source code where themethod was defined. When you’re working with a complex library like Rails orSolidus, which gives you and your team access to hundreds of thousands of linesof code, this is a godsend. If I were only allowed to use one Pry feature, it’dbe this one.If I want to know more about what goes into making my_order.paid? returnfalse, I now have so much more context than I had before. I can now also runbundle open solidus_core to open solidus_core in my text editor and surf theapp/models/spree/order.rb file for more context if I need it.Sometimes, the result of show-source will be less straightforward, and you maynot know what to do with the context you’re given:But you can puzzle out a lot with this: “Oh, this comes from the activemodelgem, which seems like something I read about in the Rails Guides. The methoddefinition makes me think that this is actually a generated method. So maybethat has to do with how #total is some kind of database-backed, Rails methoddefined with special Rails model magic. Interesting.”It would be negligent of me not to mention that there are other debugging toolsother than Pry, including Ruby’s own debuggem, which are powerful and good. I offer youPry specifically because a) it’s a tool that the Super Good team and I usefrequently and b) you can get up and running without having to learn much atall. I recommend checking out Pry’s screencasts and thedevhints.io Pry cheatsheet if you want to get a deeperintroduction to this tool.As you continue your Rails journey, you’ll learn to call #to_sql after querymethods, read your server logs more efficiently, and find Your Own Best Friendswhen it comes to making sense of Too Much information. So I’ll leave you thereto figure that out for yourself.Depending on what kind of application you’re going to work on, you may or maynot be extending functionality provided by external libraries. At Super Good, weoften must adjust (or clobber) ecommerce functionality provided by Solidus sothat our clients can get the most out of their completely-custom online storesand order management platforms.Ideally, the frameworks and libraries you’re using provide extension points,or other configuration options that let you add code that does whatever you wantwithout bypassing the library itself. In the real world, though, things don’talways line up like that. The Solidus Guides provide a handful ofcustomization-specific guides: one of them discusses extension points andoverrides. So,yeah. It’s canon. Sometimes you just gotta do it. But try not to if you can helpit.I can’t rightly talk much more about extension points. Every library’s extensionpoints look a little different. The best ones have documentation that help youuse them, or tell you how not to use them. In Solidus, there’s a whole class,Spree::AppConfiguration full ofextension points. Many of them provide a default class or function that you canswap out for code that you keep in your own application:If you wanted to provide your own order merger functionality, you can set thatconfiguration option in an initializer:Then, wherever you seeSpree::Config.order_merger_class in theSolidus source code, you’ll be using your class instead of the default oneprovided by Solidus.In a section above, we already discussed how it’s worth understanding howModule#include, Module#prepend, and friends, work so you can understandwhere Ruby functionality is coming from when you read and write new features.If you need to change an existing class or module, or one that you’re inheritingfrom a dependency, these tools can help—but be careful, as you really areoverriding the authored behaviour.Since Rails 6, there are more easy-on-the-eyes, easier-to-skim ways to prependadditional functionality onto existing classes and modules usingActiveSupport::Concerns:My advice is to always prefer isolating your application code from codeprovided by dependencies. It makes gem upgrades more straightforward. It is lesserror prone generally. When you do resort to overrides, fight Rails and yourdependencies as gently as possible. Also don’t forget that, when it comes tore-defining existing methods: super is a good friend to have.If you’re just beginning your Ruby or Rails adventure, I hope this post has beenhelpful and encouraging. Below I’ve included the links scattered throughout thisarticle into a “three-week plan” of sorts.Learning Ruby:Recommended tools for week 1:Learning Rails:Ruby testing tools to familiarize yourself with:More fun with Pry:Real, open source Rails application codebases:Extra credit:The debug gemRuby’s own debug gem, which adds a lot of functionality to IRB.Getting Started with EnginesSolidus is a Rails engine. Solidus extensions are Rails engines. This is howthey work.Mastodon’s rails_helper.rb fileSee anything you don’t understand? How would you figure out all of the stuff you don’t understand?Customizing the Solidus coreSolidus’s Spree::AppConfiguration classCheck out how you can swap out entire classes using configuration points.Here’s anexampleof one such configuration point in Solidus’s Spree::Order source code.See lots of stuff you don’t recognize? How do you go about fixing that?



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

From Developer to Rails Developer, and Then Some

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×