Tag: Ruby Pigeon

Object#tap And How To Use It

— Tags: Ruby Pigeon, Ruby

The #tap method was introduced in Ruby 1.9, back in 2007. To this day, it raises questions like:

  • What does it do?
  • How is that even remotely useful, and when would I ever use it?
  • Why is it named so terribly?

After reading this article, you will be able to answer these questions.

Private Is For Humans

— Tags: Ruby Pigeon, Ruby

A friend told me a tale about a technical job interview from years ago. The feedback he received from the interviewer was that he had used private incorrectly. The code was something like this:

class FizzBuzz
  def generate
    # ...
  end

  private

    FIZZ = 3
    BUZZ = 5

    # ...
end

Constants can be made private using private_constant.

The interviewer had correctly identified that the FIZZ and BUZZ constants were still publicly accessible. In Ruby, private does not affect constants.

# constants are accessible from outside the class
FizzBuzz::FIZZ #=> 3

Class methods are also not affected by private, but can be made private using private_class_method or class << self syntax.

Even so, this usage of private is not “incorrect”. What the interviewer failed to identify is that private is for humans. Let’s look at why, on today’s episode of This Ain’t It, Chief.

My Beef With RuboCop

— Tags: Ruby Pigeon, Ruby

Consider a hypothetical class that filters out unsafe HTML elements:

class SanitizingFilter < HTMLFilter
  def render_element(name, attrs, content)
    if safe?(name, attrs)
      super
    else
      nil
    end
  end
end

The default RuboCop settings would have us change it to this:

class SanitizingFilter < HTMLFilter
  def render_element(name, attrs, content)
    super if safe?(name, attrs)
  end
end

Let us feast on a three-course meal of opinion about why this is worse.

ValueSemantics—A Gem for Making Value Classes

— Tags: Ruby Pigeon, Ruby

Today I am announcing ValueSemantics — a gem for making value classes. This is something that I’ve been using in my personal projects for a while, and I think it’s now ready for public use as of v3.0.

In this article, I will give an overview of the gem, but I mainly want to talk about the thought process behind designing a library. We’ll look at:

  • features
  • design goals
  • comparisons to similar gems
  • the module builder pattern
  • case equality
  • callable objects
  • opinions about freezing
  • Integration Continuity™
  • designing DSLs
  • stability in cross-cutting concerns

Dependency Injection Containers vs Hard-coded Constants

— Tags: Ruby Pigeon, Ruby

Dependency injection (DI) is a somewhat contentious topic in the Ruby community. Some argue that DI containers are unnecessary complexity cargo-culted from Java. Some argue that DI is the path to cleaner, simpler, more-testable code.

In this article, I want to compare and contrast two approaches: hard-coded constants versus using a DI container. The difference might not be as big as you think!

Let’s start with a quick explanation of DI, and DI containers.

Testing Example Code In Your Jekyll Posts

— Tags: Ruby Pigeon, Ruby, Testing

Blocks of code in blog posts and articles often contain errors. I see it frequently, in other people’s writing and my own. Code examples are usually not tested, or even run through a compiler/interpreter, so errors are not surprising.

I’d like my code examples to be as good as the real code that I write. Ideally, all code examples would have tests, which are run before the site is deployed, as part of a CI build process.

And so, I created a Jekyll plugin to enable that workflow.

Replacing Mocks With Hand-Written Test Doubles

— Tags: Ruby Pigeon, Ruby, Testing

Consider the following test.

RSpec.describe Commands::StartRecording do
  it "spawns one recording process per camera" do
    expect(ProcessManager).to receive(:spawn).with(/camera_11/).and_return(123)
    expect(ProcessManager).to receive(:spawn).with(/camera_22/).and_return(456)
    allow(ProcessManager).to receive(:exists?).with(123).and_return(true)
    allow(ProcessManager).to receive(:exists?).with(456).and_return(true)

    result = Commands::StartRecording.(cameras: [11, 22])

    expect(result).to be_successful
  end

  # (more tests here)
end

I will be using RSpec in this article, but the concept applies equally well to Minitest.

This test checks that Commands::StartRecording spawns multiple processes via ProcessManager. We don’t want to actually spawn any processes during testing, so methods on ProcessManager have been mocked out using RSpec Mocks.

There are a few problems with this test.

Super Secret Methods

— Tags: Ruby Pigeon, Ruby

Here is a quirk of the Ruby language that I discovered a few weeks ago.

Method names can not contain a period character.

def secret.squirrel
  :shhh
end
#=> undefined local variable or method `secret' (NameError)

This is because the period character is syntax used for defining methods on specific objects.

secret = "hello"
def secret.squirrel
  :shhh
end

p secret #=> "hello"
p secret.squirrel #=> :shhh

Even though the syntax does not allow periods in the method name, surprisingly, the Ruby runtime will allow it. Using define_method, the syntax limitations can be bypassed.

# this works
define_method('secret.squirrel') do
  :shhh
end

The method above can’t be called using normal Ruby syntax.

secret.squirrel
#=> undefined local variable or method `secret' (NameError)

But again, the syntax limitations can be bypassed, using send.

p send('secret.squirrel') #=> :shhh

To summarize, it is possible to define and call methods that are impossible to access via normal Ruby syntax.

Result Objects - Errors Without Exceptions

— Tags: Ruby Pigeon, Ruby

In Ruby, errors and failures are typically implemented with exceptions. In some situations, however, exceptions may not be the best choice. This article covers some of the problems with exceptions, and introduces a functional, alternative approach to error handling.

How To Make A DSL, Hygienically

— Tags: Ruby Pigeon, Ruby

In this article, I’m going to show you how to implement a DSL like this:

xml version: '1.0', encoding: 'UTF-8'

weather at: @time.iso8601 do
  description @description
  temperature "#{@temp} C"
  wind do
    velocity "#{@wind_vel} kts"
    direction @wind_direction
  end
end

That produces XML like this:

<?xml version="1.0" encoding="UTF-8"?>
<weather at="2016-11-29T22:54:15+11:00">
  <description>Bright &amp; sunny.</description>
  <temperature>18.3 C</temperature>
  <wind>
    <velocity>14 kts</velocity>
    <direction>SSE</direction>
  </wind>
</weather>

Using code like this:

template = RXT::Template.from_file('weather.rxt')
puts template.render(
  time: Time.now,
  description: 'Bright & sunny.',
  temp: 18.3,
  wind_vel: 14,
  wind_direction: 'SSE',
)

I’ve given this Ruby XML templating language a spicy, exotic name: Ruby XML Template (RXT).

I know, XML doesn’t make for the most exciting DSL, and the usefulness of this particular DSL is questionable. But it will do nicely for the purpose of demonstration. It gives me the opportunity to showcase some of the more bendy, flexible parts of Ruby.

All the code is available on GitHub: tomdalling/ruby_xml_template

Q&A With Piotr Solnica

— Tags: Ruby Pigeon, Ruby

I recently had the pleasure of chatting with Piotr Solnica about Ruby, Rails, dry-rb, functional programming, and the Ruby community.

Piotr is a seasoned Ruby developer, with around a decade of Rails experience. He is the creator of Ruby Object Mapper (ROM) and one of the founders of dry-rb.

What I find interesting about Piotr’s work is how it incorporates concepts that are somewhat-foreign to the typical Rails developer. Rails has dominated the Ruby ecosystem for a long time, but it is just one tiny part of the overall software development industry. Piotr, and developers like him, play the important role of breathing fresh air into our community.

Without further ado, I’m proud to present: Q&A with Piotr Solnica.

Screencast: Debugging With Byebug

— Tags: Ruby Pigeon, Ruby

There are a few different approaches to hunting down bugs.

There’s the change things at random and see what happens approach, which is popular with beginners, but not very effective.

Then there’s puts debugging, where you add code to print things out at certain points, and try to diagnose the problem based on the output. This is a fine approach, despite some annoyances. When you don’t know what the problem is yet, it can be hard to guess what you need to print out. Sometimes you have to dig through lots of unrelated output to find what you’re looking for. It often involves editing lots of different files, maybe even files inside thirdparty gems. And at the end, once you’ve solved the issue, you have to find and remove all the printing code you added.

There’s also raise debugging, which is the same as puts debugging except that you raise exceptions with messages instead of printing output.

In this screencast I want to show you a different, more sophisticated way to debug Ruby code using Byebug.

Wasting Time TDDing The Wrong Things

— Tags: Ruby Pigeon, Ruby, Testing

When learning TDD, you usually start by testing small, individual classes. Exercises like these are designed to get you into the workflow quickly, without much hassle.

When you transition from small exercises to real-world work, however, things quickly get hairy.

A typical scenario goes something like this. You don’t know where to start, so you guess which classes you will need, and randomly pick a small one to begin with. A few red/green/refactor cycles later, and everything looks good! You successfully TDD’d a bunch of little classes. You just need to tie them all together, and you’ll be done – except they don’t fit together properly. You had a rough idea about the overall structure you were aiming for, but now you realise that isn’t going to work. Maybe you didn’t fully understand what you were trying to build, and now that you’ve built it, it technically works but doesn’t do what it was supposed to. You probably need to throw away a bunch of code that you just spent hours implementing and testing, and write it again. Or even worse, it might be 5:26pm on a Friday, tempting you to hack it all together and call it a day.

How can you “test first” if you don’t know exactly what you’re testing? If TDD is supposed to help with design, how can it lead you down the wrong path like this?

Minitest Cheat Sheet

— Tags: Ruby Pigeon, Ruby, Testing

After creating cheat sheets for RSpec::Core and RSpec::Expectations, I think it is only fair to have a cheat sheet for Minitest too.

Minitest also provides an optional RSpec-like DSL, which is not covered here.

Minitest is a small (some might say “mini”) testing framework, where tests are written in “plain Ruby,” as opposed to using a custom DSL. It has a gentler learning curve than RSpec, and is the default testing framework for Rails.

This cheat sheet covers basic test structure, the default assertions, class-level options, and writing custom assertions. The code was written against Minitest 5.9.1.

A Definition Of Magic

— Tags: Ruby Pigeon, Ruby

Magic is an intangible quality of a codebase. Sometimes it’s amazing, allowing you to implement complicated functionality in just a few lines of code. Other times it’s scary, confusing, or frustrating.

Rails and Ruby are often accused of being “too magical,” but what does that mean, exactly? Here, I’d like to make the term more tangible by putting forward a definition: magic is implicitness without understanding.

Raise On Developer Mistake

— Tags: Ruby Pigeon, Ruby

To raise, or not to raise – that is the question:
Whether ‘tis nobler in the mind to suffer
The slings and arrows of outrageous return values,
Or to take arms against a sea of non-local control flow

– Shakespeare (paraphrased)

When is it appropriate to raise an exception? This is a question that every programmer faces. It’s a complicated topic, with multiple, differing opinions. Here, I want to focus on just one aspect: giving feedback to future developers.

Examining The Internals Of The Rails Request/Response Cycle

— Tags: Ruby Pigeon, Ruby

Come with me on a journey through the internals of Rails, as we trace a request from the web server to the controller action method, and follow the response back again. This will give you a glimpse of how Rails works under the hood, hopefully exposing some of the “magic” of the framework. We will also get to see some of the design/architectural decisions at the core of Rails.

This analysis was conducted against a newly generated Rails 5.0.0.1 app.

The Pure Function As An Object (PFAAO) Pattern

— Tags: Ruby Pigeon, Ruby

In Ruby, all functions are methods, so the terms “function” and “method” are interchangeable in this article.

In this article, I want to demonstrate a nice way to write functional-style code in Ruby. It is a way to write non-trivial pure functions, without a bunch of weird non-idiomatic code.

I’ll start by defining what pure functions are, explaining their benefits, and then walk through an example implementation.

My Rails Models Are Bloated. Should I Use Concerns?

— Tags: Ruby Pigeon, Ruby

tl;dr Probably not. It’ll just make the code worse.

The typical scenario goes something like this:

In the beginning, you implement new functionality by adding methods to your model classes. That’s what DHH does, so it can’t be that bad. And it works fine… for a while.

Your web app is a lot larger now, and the model classes are growing out of control. The User model is especially big. The app/models/user.rb file is thousands of lines long. You dread making changes to the larger model classes because they are hard to understand, and easy to break.

You decide it’s time to refactor those painful model classes. You look at what Rails provides, and find only one tool for the job: ActiveSupport::Concern.

The word “concern” has other meanings in the context of programming, but when I use it in this article I’m referring to ActiveSupport::Concern. It’s unfortunate that Rails chose to coopt the word.

Concerns look good. Functionality will get extracted out into smaller modules, making the model classes smaller too. That’s the goal: to turn one big complicated piece of code into smaller, simpler pieces of code.

So, will concerns make your model classes simpler, and easier to work with? Probably not.

RSpec Expectations Cheat Sheet

— Tags: Ruby Pigeon, Ruby, Testing

Continuing the from the previous post, here is a cheat sheet for RSpec’s assertion library: RSpec::Expectations.

RSpec is a mature, feature-packed testing framework, but the documentation can be difficult to navigate. As an alternative to the official documentation, this cheat sheet contains short example code to demonstrate all the built-in expectation matchers.

These examples were created with RSpec 3.5. All of the examples are passing – there are no examples of failing tests. They cover the functionality in RSpec::Expectations – functionality for expressing assertions inside tests using expect. For examples of RSpec.describe, it, let, etc., see the previous post: RSpec::Core Cheat Sheet.

RSpec::Core Cheat Sheet

— Tags: Ruby Pigeon, Ruby, Testing

RSpec is a mature, feature-packed testing framework, but the documentation can be difficult to navigate.

The official documentation is written as a set of Cucumber tests within Relish. It’s very comprehensive, but also quite sparse, and Cucumber tests are kind of unnatural to read.

When I forget how to do something in RSpec, I usually just look for an example in a test I’ve written previously, so I thought it would be nice if there was a single place with short example code for all the features, and this is it!

These examples were created with RSpec 3.5. They cover the functionality in RSpec::Core – functionality for structuring tests with describe, it, context, let, before and after hooks, etc. It doesn’t cover all the different matchers used with expect, so if that’s what you’re looking for, check out the next post: RSpec::Expectations Cheat Sheet.

Isolate Side Effects – Functional Style in Ruby

— Tags: Ruby Pigeon, Ruby

In this article, we’ll look at what side effects are, why they are problematic despite being necessary, and how to isolate them to minimise their drawbacks.

This is part of a series about to incorporating functional programming concepts into Ruby code, in a pragmatic way – something I call “functional style.”

Avoid Mutation – Functional Style In Ruby

— Tags: Ruby Pigeon, Ruby

This article is about incorporating functional programming concepts into Ruby code, in a pragmatic way – something I call “functional style.”

And when I say pragmatic, what I mean is that the code should still mostly look and feel like idiomatic Ruby. Ruby is not Haskell, and nor should it be. The idea is to work with the grain of the language, not against it. The code should be easy for any Rubyist to understand – hopefully even easier than what you’re accustomed to.

So let’s look at avoiding mutation: the benefits, how to do it, the drawbacks, and where it might not be appropriate.

A Review Of Immutability In Ruby

— Tags: Ruby Pigeon, Ruby

Shared mutable state is the source of a lot of bugs. When two or more objects use the same piece of mutable data, they all have the ability to break each other in ways that can be hard to debug. If the shared data is immutable, however, these objects can not affect each other, and are effectively decoupled.

This article is a review of the options available to Rubyists regarding immutability. We’ll look at the built-in features of Ruby 2.3, and a few gems.

4 Ways To Avoid Monkey Patching

— Tags: Ruby Pigeon, Ruby

In Ruby land, monkey patching is the act of modifying the methods on someone else’s class. Ruby makes it easy to add, remove, and replace methods on any class – even core classes like Array – but it is generally frowned upon. It can be very difficult to debug problems caused by monkey patching, and it can easily cause bugs when the patched class changes.

If you’re considering monkey patching but you know it’s a bad idea, here are four alternatives in order from most preferable to least preferable.

How To Implement Simple Authentication Without Devise

— Tags: Ruby Pigeon, Ruby

Almost every web app requires a sign in form. In Ruby, the popular choice is the Devise gem for Rails.

Devise gives you a lot of functionality out of the box, but it can also be frustrating. It has a lot of “magic,” and is heavily coupled to various parts of Rails. If you’re requirements don’t exactly fit the gem – for example, anonymous users – you will be wading through documentation, how-to’s, and the source code of a few gems. That’s no fun, and it might be more trouble than it’s worth. And when that auth-related change request appears in a few months, will it be easy, or will you be facing a maintenance nightmare?

Authentication is actually pretty simple! If you have minimal requirements, you can roll your own authentication with less than 100 lines of code. In this article, I’m going to show you a tiny web app featuring sign in, sign out, and new user creation, with a sweet and simple manual implementation.

All the source code is available as a single-file here: simple_authentication.rb