I’m no Ruby engineer however even as a front-end developer I’m sometimes called upon to work on Rails applications that require me to know my way around. Here are my notes and reminders.
This is not intended to be an authoritative guide but merely my notes from various lessons. It’s also a work-in-progress and a living, changing document.
Table of contents #
- The Rails Console
- blank? vs empty?
- Class-level methods
- Instance Variables
- Empty-checking arrays
- The Shovel Operator
- Rendering HTML
- Generating random IDs or strings
- Start local Rails server
- Web fonts location
- Working with the Database
The Rails Console #
console command lets you interact with your Rails application from the command line.
Quickly find where a method is located:
See an object’s methods:
Run it like so:
If adding data variables to use in tests, declare them in a let block so as to keep them isolated and avoid them leaking elsewhere.
Note: if you need multiple data variables so as to handle different scenarios, it’s generally more readable to define the data being tested right next to the test.
Helper methods are to there to support your views. They’re for extracting into methods little code routines or logic that don’t belong in a controller and are too complex or reusable to be coded literally into your view. They’re reusable across views because they become available to all your views automatically.
Don’t copy and reuse method names from other helpers. You’ll get conflicts because Helpers are leaky. Instead, start your helper methods with an appropriate namespace.
Unlike object methods (e.g.
myobj.do_something) helper methods (e.g.
render_something) are not available for us to use in the Rails console.
Helper specs #
- start with
describe: it’s a good top-level.
- describe a helper method using hash (
describe "#project_link" do)
- Helper methods should not directly access controller instance variables because it makes them brittle, less reusable and less maintainable. If you find you’re doing that you might see it as an opportunity to refactor your helper method.
Debugging Helper methods #
If you want to debug a helper method by running it and stepping through it at the command line you should lean on a test to get into the method’s context.
blank? versus empty? #
If you want to test whether something is “empty” you might use
empty? if you’re testing a string, however it’s not appropriate for testing object properties (such as
person.nickname) because objects can be
nil and the
nil object has no
empty? method. (Run
nil.empty? at the console for proof.) Instead use
frozen_string_literal: true #
I’ll often see this at the top of files, for example Ruby classes. This is just a good practice. It makes things more efficient and thereby improves performance.
Class-level methods #
They’re called class-level methods because they are methods which are never called by the instance, i.e. never called outside of the class. They are also known as macros.
attr_reader and ViewComponent’s
Here’s an example where we define a new constant and assign an array to it.
Interestingly while the constant cannot be redefined later—i.e. it could not later be set to something other than an array—elements can still be added or removed. We don’t want that here. The following would be better because it locks things down which is likely what we want.
They’re not variables. They’re more like strings than variables however Strings are used to work with data whereas Symbols are identifiers.
You should use symbols as names or labels for things (for example methods). They are often used to represent method & instance variable names:
From what I can gather, colons identify something as a Symbol and the colon is at the beginning when its a method name or instance variable but at the end when its a hash key.
ViewComponents (specifically the
my_component.rb file) are just controllers which do not access the database.
They use constructors like the following:
(Note that you would never include a constructor in a Rails controller or model.)
ViewComponents in the Rails console #
Instance variables #
def initialize(foo: nil)
@foo = foo
In the above example
@foo is an
instance variable. These are available to an instance of the controller and private to the component. (This includes ViewComponents, which are also controllers.)
In a view, you can refer to it using
In a subsequent method within the controller, refer to it simply as
foo. There’s no preceding colon (it’s not a symbol; in a conditional a symbol would always evaluate to
true) and no preceding
classes = ["myThing"]
classes << "myThing-foo" if foo
Making instance variables publicly available #
The following code makes some instance variables of a ViewComponent publicly available.
However although that’s the pattern employed by the ViewComponent website you could argue it’d be better not to do this because it makes more stuff public than needs to be. Instead you could simply access the instance variables directly (including in the view). I’d like to dig into this one a bit more and just check I’m clear on the syntax (perhaps
Every method returns a value. You don’t need to explicitly use
return, because without it it will be assumed that you’re returning the last thing in the method.
Define private methods #
private above the instance methods which are only called from within the class in which they are defined and not from outside. This makes it clear for other developers that they are internal and don’t affect the external interface. This lets them know, for example, that these method names could be changed without breaking things elsewhere.
Also: keep your public interface small.
Naming conventions #
The convention I have worked with is that any method that returns a
boolean should end with a question mark. This saves having to add prefixes like “is-” to method names. If a method does not return a boolean, its name should not end with a question mark.
Named Parameters #
When this method is called (in this case “when the ViewComponent is instantiated”)
- none of the parameters are mandatory.
- you need to add the parameter name before the value you’re passing e.g.
<%= render(CardComponent.new(size: :small, full_height: true)) do %>
Check if thing is an array and is non-empty #
You can streamline this to:
The shovel operator #
The shovel operator (
<<) lets you add elements to an array. Here’s an example where we build up an HTML
class attribute for a BEM-like structure:
require allows you to bring other resources into your current context.
do…end structure in Ruby is called a “block”, and more specifically a multi-line block.
Blocks are essentially methods (functions).
We can specify that a block must be present. For example:
Here, the ampersand (
&) means that the block is required.
Single-line block #
Sometimes we don’t need to use a multiline block. We can instead employ a single-line block. This uses curly braces rather than
For example in a spec we might use:
The above two lines really just construct a “string” of the component and let you test for the presence of things in it.
Rendering HTML #
We have the
content_tag helper method for rendering HTML elements. However you are arguably just as well coding the actual HTML rather than bothering with it, especially for the likes of
link_to is a little more useful and makes more sense to use.
send() is not just for use on
tag. It’s a means of calling a method dynamically i.e. using a variable. I’ve used it so as to have a single line create either a
th or a
td dymamically dependent on context.
Only use it when you are in control of the arguments. Never use it with user input or something coming from a database.
Random IDs or strings #
object_id gives you the internal ruby object id for what you’re working on. I used this in the past to append a unique id to an HTML
id attribute value so as to automate an accessibility feature. However don’t use it unintentionally like I did there.
It’s better to use something like
If you have logic you need to use in a view, this would tend to live in a helper method rather than in the controller.
You might create a method such as
allowed_to? for purposes of authorisation.
Start (local) Rails server #
Note: the following is shorthand for
bin/rails server -b 0.0.0.0.
Use Ruby to create a local web server.
Web fonts: where to put them in the Rails file structure #
The Database #
Reset/wipe the database.
Get routes for model from terminal #
Let’s say you’re working on the index page for
pet_foods and want to create a sort-by-column anchors where each link’s
src points to the current page with some querystring parameters added. You’re first going to need the route for the current page and in the correct format.
To find the existing routes for
pet_foods you can run: