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
- Rspec
- Debugging
- Helpers
- blank? vs empty?
- frozen_string_literal
- Class-level methods
- Constants
- Symbols
- Hashes
- ViewComponent
- Instance Variables
- Methods
- Empty-checking arrays
- The Shovel Operator
- Require
- Blocks
- Rendering HTML
- Generating random IDs or strings
- Views
- Policies
- Start local Rails server
- Miscellaneous
- Web fonts location
- Working with the Database
- Routing
- References
The Rails Console
The 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:
Rspec
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.
Debugging
I’ll cover debugging related to more specific file types later but here’s a simple tip. You can check the value of a variable or expression at a given line in a method by:
- add
byebug
on a line of its own at the relevant place in your file, then save file - switch to the browser and reload your page
- in the terminal tab that’s running the Rails server (which should now be stopped at the debugging breakpoint), at the bottom type the variable name of interest. You won’t see any text but just trust that your typing is taking effect. Press return
- you’ll now see the value of that variable as it is at the debugging breakpoint
- When you’re done, remove your
byebug
. You may need to type continue (orc
for short) followed by return at the command prompt to get the server back on track.
Helpers
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
Basic format:
Notes:
- 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 blank?
e.g. person.nickname.blank?
.
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.
Examples include attr_reader
and ViewComponent’s renders_one
.
Constants
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.
Symbols
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.
Hashes
A Hash is a dictionary-like collection of unique keys and their values. They’re also called associative arrays. They’re similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type.
Example:
hash = {a: 1, b: 2, c: 3}
The fetch method for Hash
Use the fetch method as a neat one-liner to get the value of a Hash key or return something (such as false) if it doesn’t exist in the hash.
ViewComponents
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)
super
@foo = foo
end
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 @foo
.
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 @
.
def classes
classes = ["myThing"]
classes << "myThing-foo" if foo
classes
end
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 card.size
).
Methods
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
Add 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.
Parameters
The standard configuration of method parameters (no colon and no default value) sets them as required arguments that must be passed in order when you call the method. For example:
By setting a parameter to have a default value, it becomes an optional argument when calling the method.
Named Parameters
Configuring your method with named parameters makes the method call read a little more clearly (via the inclusion of the keywords in the call) and increases flexibility because the order of arguments is not important. After every parameter, add a colon. Parameters are mandatory unless configured with a default value.
Here’s an example.
And here’s how you might do things for a Card
ViewComponent.
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:
Double splat operator
My understanding is that when you pass **foo
as a parameter to a method call then it represents the hash that will be returned from a method def foo
elsewhere. The contents of that hash might be different under different circumstances which is why you’d use the double-splat rather than just specifying literal attributes and values. If there are multiple items in the hash, it’ll spread them out as multiple key-value pairs (e.g. as multiple HTML attribute name and attribute value pairs). This is handy when you don’t know which attributes you need to include at the time of rendering a component and want the logic for determining that to reside in the component internals. Here’s an example, based on a ViewComponent for outputting accessible SVG icons:
In the icon_component.html.erb
template:
The **aria_role
argument resolves to the hash
output by the aria_role
method, resulting in valid arguments for calling Rails’s tag.svg
.
require
require
allows you to bring other resources into your current context.
Blocks
The do…end
structure in Ruby is called a “block”, and more specifically a multi-line block.
<%= render CardComponent.new do |c| %>
Card stuff in here.
<% end %>
Blocks are essentially methods (functions).
We can specify that a block must be present. For example:
def has_block(param, &block)
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 do…end
.
For example in a spec we might use:
render_inline(CardComponent.new) { "Content" }
expect(rendered_component).to have_css(".fe-CardV2", text: "Content")
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 div
and span
elements.
link_to
is a little more useful and makes more sense to use.
Multi-line HTML string
Return a multi-line HTML string like so:
output = "<p>As discussed on the phone, the additional work would involve:</p>
<ol>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ol>
<p>This should get your historic accounts into a good shape.</p>".html_safe
output
Interpolation
Here’s an example where we use interpolation to return a string that has a text label alongside an inline SVG icon, both coming from variables.
"#{link[:text]} #{icon_svg}".html_safe
tag.send()
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 rand
, or SecureRandom
or SecureRandom.hex
.
Views
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.
Policies
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
.
rails s
Miscellaneous
Use Ruby to create a local web server.
# to serve your site at localhost:5000 run this in the project’s document root
ruby -run -e httpd . -p 5000
Web fonts: where to put them in the Rails file structure
See https://gist.github.com/anotheruiguy/7379570.
The Database
Reset/wipe the database.
bundle exec rake db:reset
Routing
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:
rails routes | grep pet_foods