Rubyland

news, opinion, tutorials, about ruby, aggregated
Sources About
Appfolio Engineering 

Ruby 2.7 and the Compacting Garbage Collector

Aaron Patterson, aka Tenderlove, has been working on a compacting garbage collector for Ruby for some time. CRuby memory slots have historically been quirky, and may take some tweaking - this makes them a bit simpler since the slot fragmentation problem can (potentially) go away.

Rails Ruby Bench isn’t the very best benchmark for this, but I’m curious what it will show - it tends to show memory savings as speed instead, so it’s not a definitive test for “no performance regressions.” But it can be a good way to check how the performance and memory tradeoffs balance out. (What would be “the best benchmark” for this? Probably something with a single thread of execution, limited memory usage and…

Remote Ruby 

Joined by Piotr Solnica

Awesome Ruby Newsletter 

Issue 165 - Goodbye ActiveRecord! - Inside Aircall - Medium

code.dblock.org | tech blog 

Asserting Existence with Mocha, Chai and TypeScript Strict Null Checks

I recently encountered a unit test that looked like this.

describe("Spline", () => {
  const spline = new Spline();

  it("can be reticulated", () => {
    const reticulatedSpline = spline.reticulate();
    if (! reticulatedSpline) {
      throw new Error('missing a spline');
    }
    expect(reticulatedSpline.reticulatedCount).to.eq(1);
  });
});

The use of branching and conditionals in tests is an anti-pattern since we want tests to be predictable, each test to focus on a single code execution path and generally keep things simple.

The obvious solution is to replace the conditional with .to.not.be.null or .to.not.be.undefined or the catch-all .to.exist (less cognitive overhead). So why…

OmbuLabs Blog 

A Gentle Introduction To Docker

If you're like I was not too long ago, the DevOps world gives you a chance to experience what most non-developers probably feel like when they read about what we do on a day to day basis - confused, and maybe a little bored and frustrated, with an utter lack of even basic knowledge. It doesn't help that DevOps is rapidly becoming a field of expertise unto itself, or that most of the relevant players seem determined to hide behind vague descriptions like "enterprise platform" and "containerization solution." As a day to day working developer, adding an entire new skillset can be a daunting and intimidating prospect.

Fear not, though. Getting some basic knowledge is not as hard as it might…

Ruby Weekly 

Tenderlove digs deep into the Ruby runtime

#459 — July 18, 2019

Read on the Web

Ruby Weekly

regexp-examples: Generate Strings That Match a Given Regular Expression — This isn’t new but it’s just had a update to support the latest Ruby and I’ve always loved the idea. Given a regular expression, use the examples method to see some strings that would match the expression. For example: /ab+/.examples == ['ab', 'abb', 'abbb']

Tom Lord

GraphQL on Rails: On The Way to Perfection — The conclusion to a three part series (part one is here) on building GraphQL-based apps with React and Rails. This last outing focuses on some significant refactorings,…

Dmitry Tsepelev…

Semaphore 

Tim Cheadle on scaling an Open Source mobile app and his commitment to community-focused software

We talk with Tim about his current projects, aspects of continuous delivery in the mobile app context and creating community-focused software.

You’re currently working as Director of Engineering at Resolve to Save Lives and leading on the development of the Simple mobile app. Please let us know more about this Open Source project and how does it actually save people’s lives?

Resolve to Save Lives is a global non-profit with the goal of saving 100 million lives by improving cardiovascular health. Heart disease kills more people than anything else, but it doesn’t have to be that way. We know that high blood pressure is a leading cause of heart disease, and we also know how to treat it.…

Mike Perham 

Proxying Golang Web Applications

Recently someone posted an issue asking if Faktory could support putting nginx in front of Faktory's Web UI. Normally you access the Web UI like http://localhost:7420/ but they wanted it to look something like http://somehost:8080/faktory. That's quite common when trying to wrap multiple systems into something that looks like one website to the browser.

The issue is that the Web UI assumed it was at the root, so it hardcoded paths like /static/application.css. If you mount the Web UI at /faktory, you want that CSS URL to become /faktory/static/application.css.

After thirty minutes of Googling, I could find nothing on how to solve this problem so I put on my thinking cap and ground it…

With a Twist 

Reporting from ephemeral containers in production

Reporting is not a particular task of business analysts anymore. Anyone at any department, at any point in time, needs a quick report based on the latest data to validate their decisions. Having the ability to create small custom reports in a couple of minutes, and in a format that can be consumed by any analysis software is a powerful resource to have in our belt. The goal is to run this kind of reports without having too much overhead that would kill our productivity, and without having to learn a new set of libraries or tools.

Platform as a service (PAAS) environments like Aptible or Heroku only give you an ephemeral container when accessing the console, which means that changes to the…

Honeybadger Developer Blog 

How We Migrated To Turbolinks Without Breaking Javascript

It's 2019, so we decided it was time to take a more modern approach to the Honeybadger front end. We implemented Turbolinks! This is only the first step on an ambitious roadmap. In 2025 we plan to migrate to Angular 1, and we'll finish out the decade on React unless we run into any roadblocks!

But let's get real. Honeybadger isn't a single page app, and it probably won't ever be. SPAs just don't make sense for our technical requirements. Take a look:

  • Our app is mostly about displaying pages of static information.
  • We crunch a lot of data to generate a single error report page.
  • We have a very small team of four developers, and so we want to keep our codebase as small and simple as possible.

The Days of PJAX

There's an approach we've been using for years that lets us have our cake and eat it too. It's called PJAX, and its big idea is that you can get SPA-like speed without all the Javascript. When a user clicks a link, the…

Ruby on Rails Podcast 

279: Scaling & Training Rails with Anand Dhillon

Anand Dhillon is responsible for technical development and strategy at Cover as the CTO & Co-Founder. He guested on the podcast this week to discuss Domain Drive Design, Event Driven Architecture and how he implemented machine learning at Cover.

Links for this episode:

Brought to you by:

Hoefler&Co

A good font is one of the best ways to make your project stand apart. At typography.com, you'll find the work of Hoefler&Co, creators of stylish and high-performance typefaces. And now for a…

Drivy Engineering 

How Kotlin's Coroutines help us to deal with Bluetooth

At Drivy, we want to enable users to open the car even if it’s on the bottom floor of the deepest, underground parking. Since we can’t rely on a GSM connection when so deep underground, we need to use a Bluetooth connection.
But communicating with a Bluetooth device is easier said than done, due to the fact that it’s low-level and requires many asynchronous calls. Let’s see how we can improve this.

Bluetooth 101

Bluetooth communication is not exactly like HTTP communication. We don’t have URLs or ports. All we have are services and caracteristics. And UUIDs, lots of UUIDs.

According to the official doc, Bluetooth GATT services are collections of characteristics and relationships to other…

RubySec 

Remote command execution via filename

JetRockets 

How to handle 401 unauthorized error in a Redux React application

All Ruby Podcasts by Devchat.tv 

RR 421: Scaling and Shopify with Kir Shatrov

Sponsors

Panel

  • Charles Max Wood

  • Nate Hopkins

  • Andrew Mason

With Special Guest: Kir Shatrov

Episode Summary

Today’s guest Kir Shatrov is a production engineer on Shopify based in London, UK. Today, he and the panel are discussing capacity planning. Kir believes that capacity planning becomes a priority when your company starts losing money and your customers are suffering. When someone does get to the point of scaling their app, it’s important to look at the limitations of the hosting…

Semaphore 

Kubernetes Deployments: The Ultimate Guide

Ready to deploy that app you’ve just “dockerized”? Here’s all you need to know about Kubernetes deployments to deliver your containers to production.

Editor’s note: This is a guest article by Jérôme Petazzoni, a former Docker engineer, speaker and creator of container.training.

One of the first Kubernetes commands that we learn and use is kubectl run. Folks who have experience with Docker tend to compare it to docker run, and think: “Ah, this is how I can simply run a container!

As it turns out, when one uses Kubernetes:

Let’s look at what happens after running a very basic kubectl run command:

$ kubectl run web --image=nginx
deployment.apps/web created

Alright! Then…

Martian Chronicles, Evil Martians’ team blog 

GraphQL on Rails: On the way to perfection

Authors: Dmitry Tsepelev, Back-end Developer at Evil Martians and Polina Gurtovaya, Front-end Developer at Evil Martians

A hitchhiker’s guide to developing GraphQL applications with Rails on the back-end and React/Apollo on the front-end. The third and final part of this tutorial is all about real-time updates, as well as about DRY-ing up our code and implementing better error handling.

In the previous parts of this tutorial we have built the prototype of a Martian Library application: a user can dynamically manage a list of artifacts related to the Red Planet in a modern SPA-fashion. It’s not quite the time to sit back and relax though, because we still have some refactoring to do.

Riding Rails 

New contributors fixing bugs in the summer

Hey all! This is Daniel from Brooklyn, NY bringing you the latest news in Rails.

Add database_exists? method to connection adapters

The database_exists? method does what you might think—it checks whether a database exists. This will help in resolving some inconsistencies between SQLite and the other database adapters.

Share column and table names between connections

Sharing is a beautiful thing. Since connection instances are likely to share table and column names, we can store them on the class instead of on each instance. Isn’t that nice?

Fix query cache when using shared connections

Congratulations to Heinrich on their first commit to Rails!

Fix bug when combining order with exist?

Test Double | Our Blog 

Life After a Diversity and Inclusion Blunder

I recently wrote a blog post about vulnerability and imposter syndrome. Okay, that may seem like a shameless plug for my post, but I promise, it is extremely relevant. Anyway, I write this blog post, and I'm pretty happy with it. I'm so happy with it that, after it goes public, I send a Slack message to my team letting them know it's up. The team is very supportive, giving me virtual high-fives for speaking publicly about a personal experience with imposter syndrome and then it comes, the dreaded, "Hey, do you mind if I offer a small bit of feedback on your blog post?" message.

I absolutely want feedback, but I also want to be right and get scared in that moment I realize I'm not. Learning…

RubyGuides 

String Concatenation & Interpolation in Ruby (With Examples)

Combining multiple strings together is something that you have to do often in Ruby.

But how can you do that?

Well…

There are two ways:

  1. Ruby string concatenation
  2. Ruby string interpolation

Concatenation looks like this:

a = "Nice to meet you"
b = ", "
c = "do you like blueberries?"

a + b + c

# "Nice to meet you, do you like blueberries?"

You can use the + operator to append a string to another.

In this case, a + b + c, creates a new string.

Btw, you don’t need to use variables to make this work.

Example:

puts "I like" + " " + "chocolate"

# I like chocolate

Another option is to use the += operator.

Example:

a = ""

a += "test"
a += "test"
a += "test"

a
# "testtesttest"

We start…

BigBinary Blog 

Rails 6 adds ActiveRecord::Relation#annotate

This blog is part of our Rails 6 series. Rails 6.0.0.rc1 was recently released.

Rails 6 has added ActiveRecord::Relation#annotate to allow adding comments to the SQL queries generated by the ActiveRecord::Relation instance.

Here is how it can be used.

>> User.annotate("User whose name starts with 'A'").where("name LIKE ?", "A%")

SELECT "users".* FROM "users"
WHERE (name LIKE 'A%')
/* User whose name starts with 'A' */
LIMIT ?  [["LIMIT", 11]]

ActiveRecord::Relation#annotate allows to add multiple annotations on a query

>> bigbinary = Organization.find_by!(name: "BigBinary")
>> User.annotate("User whose name starts with 'A'")
       .annotate("AND belongs to BigBinary organization")
Andy Croll 

Using strftime in a Rails view is probably a mistake

The strftime method appears in many languages, all the way back to C. The syntax of the (mostly impenetrable) formatting arguments haven’t changed that much in years and they’re remarkably consistent across languages.

Ruby’s version is comprehensively documented in the Time class.

However when strftime is used in your views, there’s a high chance it will lead to confusion and inconsistency.

Instead of…

…using strftime in your views to format dates and times:

<%= @user.last_signed_in_at.strftime("%m-%e-%y %H:%M") %>

Use…

…the built in Rails time and date formats. Or add to them, like I do here, creating my own :stamp format for Date and Time.

config/initializers/time_formats.rb

Date
The way is long but you can make it easy on me 

Minimum viable example of calling Rust from Ruby without a gem.

For Rubyfmt I'm currently looking at rewriting
significant sections in Rust, because there's some performance issues. Broadly
speaking, it turns out that cleaning up a very large Ruby parse tree (e.g. 4000
lines) can be slow because of the number of comparisons that have to be made.
Rust can do this a lot faster.

See https://github.com/samphippen/rubysoexperiment  if you'd like to try it out yourself.

Starting with Rust

To start with, let's imagine that I've got this rust function that I want to
call from Ruby:

pub fn return_3() -> i32 {
  return 3;
}

First, we'll need to prepare it to be used outside of Rust. By default the Rust
Compiler will rename functions, and also make them incompatible with…

Schneems - Programming Practices, Performance, and Pedantry 

Puma 4: Hammering Out H13s—A Debugging Story

For quite some time we’ve received reports from our larger customers about a mysterious H13 - Connection closed error showing up for Ruby applications. Curiously it only ever happened around the time they were deploying or scaling their dynos. Even more peculiar, it only happened to relatively high scale applications. We couldn’t reproduce the behavior on an example app. This is a story about distributed coordination, the TCP API, and how we debugged and fixed a bug in Puma that only shows up at scale.

Remote Ruby 

Joined by Chris Arcand

Heroku 

Puma 4: Hammering Out H13s—A Debugging Story

For quite some time we've received reports from our larger customers about a mysterious H13 - Connection closed error showing up for Ruby applications. Curiously it only ever happened around the time they were deploying or scaling their dynos. Even more peculiar, it only happened to relatively high scale applications. We couldn't reproduce the behavior on an example app. This is a story about distributed coordination, the TCP API, and how we debugged and fixed a bug in Puma that only shows up at scale.

Screenshot showing H13 errors

Connection closed

First of all, what even is an H13 error? From our error page documentation:

This error is thrown when a process in your web dyno accepts a connection, but then…

Awesome Ruby Newsletter 

Issue 164 - Ruby gem strong_password found to contain remote code execution code in a malicious version, further strengthening worries of growth in supply-chain attacks

OmbuLabs Blog 

Tips for Working Remotely in a Team

We have been a fully remote company for a year and a half now. Making the transition to being fully remote can be challenging for any team. During the past year and a half we have worked on making sure that our team is as productive, communicative and social as it was when we had a traditional office space. Here are some tips that we have found to be useful for remote teams:

Have a daily call: We have an office-wide scrum call every at 9:45am. We encourage employees to participate via video and to share their goals for the day and any blockers they may have. It is important for teams to have scheduled “face to face” time on a daily basis in order to stay connected. We prefer chatting in…

Time…

Mike Perham 

Leaving Twitter

Some have already noticed but I've been booted out of Twitter.

"Why, Mike?"

Because set my birth year to 2000 in my profile. I didn't think it was anyone's business, including Twitter, what my age was. Since I created the account in 2008, Twitter said I was too young to use their service and immediately locked the account.

Quite possibly the least cool way to get your account locked?

Eleven years. Tens of thousands of tweets. 9,000+ followers. Daily engagement. None of that mattered.

Yep, I can write to them asking them to unlock my account but I see this as the last straw. Free, centralized social media services will always care more about their advertisers and PR optics than they…

JetRockets 

Managing a Remote Development Team

I have been managing development projects for over fifteen years, ten of which I have spent managing remote teams. Throughout these years, I have experienced many successes, but I have also had some failures which I have always tried to use as lessons to improve my management style. I would like to share some of these lessons as tips for successful management of remote development teams.
Ruby Weekly 

Discussing Sorbet with its technical lead

#458 — July 11, 2019

Read on the Web

Ruby Weekly

strong_password v0.0.7 Ruby Gem Hijacked — Here is an example of why being diligent with your dependencies is a must. Tute was looking at the changelogs for gems in their app and found out one had been sneakily taken over. Snyk also has a good writeup of the problem.

Tute Costa

▶  Discussing Sorbet, the Ruby Type Checker, with Paul Tarjan — Two weeks ago, we covered Stripe’s open sourcing of Sorbet, a powerful type checker for Ruby. In this brief 20 minute podcast, Sorbet’s technical lead explains the project.

Ruby on Rails Podcast podcast

Stream…

Ruby on Rails Podcast 

278: Introducing Sorbet: A Ruby Typechecker with Paul Tarjan

Paul Tarjan is a lifelong nerd, juggler and engineer. Nowadays, he works at Stripe on developer productivity and infrastructural components. He is the technical lead of Sorbet, a new static type checker for Ruby.

Links for this episode:

Brought to you by:

Hoefler&Co

A good font is one of the best…

Everyday Rails 

How to TDD when TDD is hard

Sometimes, TDD gets in the way, does more to confuse than guide, or generally just slows development to a monotonous crawl. Here's a set of five go-to strategies I use to get out of test-fueled frustration, and back to productivity.
Ruby Together News 

Helping Everyone Learn To Code

Ruby Together is a non-profit trade organization that funds open source Ruby projects. This is a deep dive into one of our current funded projects including the backstory on the person who submitted the proposal and updates on project progress.

How One Woman Is Helping Everyone, Even Grandmothers, Learn To Code

It’s really important that everyone learns how to program at least a little bit. It’s going to be part of every future job. — Rachel Ober

Over 65% of new developers are self-taught. Rachel Ober is not part of that statistic. She’s among the surprising minority who learned to code in school, dual majoring in computer science and psychology—a compelling combination driven by a…

Ruby Together News 

June 2019 Monthly Update

Hello! Welcome to the monthly update. During June, our work was supported by Handshake, Stripe, Triplebyte, Bleacher Report, and many others.

ruby together news

In June, Ruby Together was supported by 57 different companies, including Sapphire member Stripe. 3 new companies joined in the last month. On top of those companies, 3 new developers joined as new members in the last month, including Balo. In total, we were supported by 119 developer members.

Thanks to all of our members for making everything that we do possible. <3

We had a quieter month in June, but both Ruby Me apprentices and Google Summer of Code students continued to work on Ruby open source projects.

bundler news

In…

Test Double | Our Blog 

Growing consultants without burning out

My career in consulting is in covered in scars.

One time I had a stakeholder scream at me on a call because we couldn’t figure out why a promised fax integration was failing (yes, it was in healthcare), all while the developer in the room with me was angrily gesticulating and mouthing swear words because the client didn’t understand. I sent daily updates for a month, paired with the developer, and demanded QA priority to expedite the delivery.

Another time, in the middle of months of long weeks and weekends, I had a VP of Product screaming at me over the phone about why a designer wasn’t delivering at the pace they expected, demanding I blame them personally. I could hear the spittle…

BigBinary Blog 

Rails 6 adds hooks to Active Job around retries and discards

This blog is part of our Rails 6 series. Rails 6.0.0.rc1 was recently released.

Before Rails 6

Before Rails 6, we have to provide a custom block to perform custom logging and monitoring around retries and discards of the jobs defined using Active Job framework.

class Container::DeleteJob < ActiveJob::Base
  retry_on Timeout::Error, wait: 2.seconds, attempts: 3 do |job, error|
    message = "Stopped retrying #{job.class} (JID #{job.job_id})
               with #{job.arguments.join(', ')} due to
               '#{error.class} - #{error.message}'.
               This job was retried for #{job.executions} times.".squish

    BackgroundJob::ErrorLogger.log(message)
  end

  discard_on Contain…
All Ruby Podcasts by Devchat.tv 

RR 420: Stimulus

Sponsors

Panel

  • Charles Max Wood

  • Dave Kimura

  • Andrew Mason

Episode Summary

Today’s topic is the Stimulus library. Stimulus is actually a JavaScript framework and library, but it’s also built by Basecamp, so it works really well in Rails. There is a demand for rich client side interactions, and Stimulus fills in some of the gaps. The panelists talk about some of their experiences with Stimulus versus jQuery. They talk about different use cases for Stimulus, how it works, and how it can…

Search Results for “ruby” – Journeys of a not so young anymore Software Engineer 

Looking for a job!

It’s that time: I’m looking for a job! You can find my CV and all relevant links over at my website: CV Web, CV PDF Quick links that might interest you: website, github, twitter and blog Who am I and why would you want to hire me? My name is Tobi, but online I’m better […]
Paweł U. | Ruby on Rails Web Development Consultant Full Stack Blog 

A Simple Way to Encrypt and Decrypt Data in Rails without using Gems

Storing sensitive data in plaintext can seriously harm your internet business if an attacker gets hold of the database. Encrypting data is also a GDPR friendly best practice. In this tutorial I will describe a simple way to securely encrypt, store, and decrypt data using built in Ruby on Rails helpers instead of external dependencies.

Avoid heavy Gem dependencies

attr_encrypted gem is a popular tool for storing encrypted data in Rails apps. The problem is that adding it to your application includes over 2k external lines of code. What’s worse is that the project has not been updated for several months at the time of writing.

Rails offers a handy ActiveSupport::MessageEncryptor class,…

The Bike Shed 

205: Won't Somebody Think of The Jokes (Aaron Patterson)

On this week's episode, Chris is joined in a live recording from RailsConf by the one and only Aaron Patterson. They discuss Aaron's many RailsConf keynotes, his recent work on Rails view rendering and his three-year-long effort to bring more advanced garbage collection to Ruby which will finally be seeing the light of day. And of course, plenty of puns.

This episode of The Bike Shed is sponsored by Indeed Prime

JetRockets 

Benefits of Custom Software

Building a custom software comes with a price tag, but the investment is often worthy. Here are the top ten reasons why.
Valentino Gagliardi 

The Little JavaScript Book: All You Need to Know About JavaScript (in less than 200 pages)

The Little JavaScript Book is the trait d’union between JavaScript for dummies and You Don’t Know JS.

The Little JavaScript Book: All You Need to Know About JavaScript (in less than 200 pages)

What is the Little JavaScript Book?

Imagine a little book, an handy reference about the “hard parts” of JavaScript. Imagine also that the book is written for beginners, in a language that’s easy and clear to understand. Done?

Lucky you because that book exists! The Little JavaScript Book is a reference for both beginners and more experienced developers about the hard parts of JavaScript. I’m working on it right now and you can read it on GitHub for free: The Little JavaScript Book.

RubyGuides 

3 Awesome Ways To Use Ruby’s Gsub Method

Let’s talk about Ruby’s gsub method.

First, you’ll need a string to play with this method.

Why?

Because you use gsub on a string to replace parts of it.

In fact:

The “sub” in “gsub” stands for “substitute”, and the “g” stands for “global”.

Got your string?

Good.

If not, you can borrow mine.

Here it is:

str = "white chocolate"

Let’s say that we want to replace “white” with “dark”.

Here’s how:

str.gsub("white", "dark")

This is saying:

Given the string str, command it to replace ALL occurrences of the first word (white) with the second word (dark).

Which means we get to eat much better chocolate.

Oh wait, it’s just a string.

We can’t eat that!

Anyway…

Ruby’s gsub method can do a lot more…

Drifting Ruby Screencasts 

Introduction to Dragon Ruby

Dragon Ruby is toolchain that allows developers the ability to build apps and games in Ruby.
avdi.codes 

Rails 6 errors: the good, the bad, the ugly

Lately when I'm supposed to be getting actually useful things done, I find myself procrastinating by writing code instead. I have a Rails 6 codebase I've been fiddling with.

The other day as I did some reload-driven-development, I got this error:

The Good

Wow, development-mode error screens have come a long way since Rails 1. There's so much information here!

First off, there's the exception, the full path, and the message.

Then a nice source code listing with the error highlighted.

Followed by a trace with selectable app and framework filters.

Then there's a bunch more essential contextual info.

Then we get to the real doozy: an interactive REPL embedded right in the error page.

I…

Riding Rails 

Schema dump fix and database task creation improvements!

Hi there. This is Greg bringing you latest news from the Rails world. We had a quiet week, so I won’t take long.

Fix schema dumping for enum and set columns in MySQL

With this change Active Record will use the sql_type rather than type, in the database dump for enum and set columns to make sure they use the correct type.

Warn if database tasks can’t be created

With this change, Rails loads the initial database.yml once, and warns if it can’t create tasks. This is important for multiple databases, where the tasks are created for every database, but to create those Rails needs to read the list from database.yml.

9 people contributed to Rails in the last week, if you want to be one of…

Code with Jason 

How to test Ruby methods that involve puts or gets

I recently saw a post on Reddit where the OP asked how to test a method which involved puts and gets. The example the OP posted looked like the following (which I’ve edited very slightly for clarity):

class Example
  def ask_for_number
    puts "Input an integer 5 or above"
    loop do
      input = gets.to_i
      return true if input >= 5
      puts "Invalid. Try again:"
    end
  end
end

What makes the ask_for_number method challenging to test is a dependency. Most methods can be tested by saying, “When I pass in argument X, I expect return value Y.” This one isn’t so straightforward though. This is more like “When the user sees output X and then enters value V, expect subsequent output…

Instead of…

code.dblock.org | tech blog 

Handling of HTTP Headers in Grape with Rack and Rails

I recently helped debug Grape#1880, an issue a developer had with HTTP headers in Grape and Rack. It wasn’t immediately obvious.

Test API

Let’s write a simple Grape API that returns a value for a header.

module Acme
  class Headers < Grape::API
    format :json

    desc 'Returns a header value.'
    params do
      requires :key, type: String
    end
    get 'headers/:key' do
      key = params[:key]
      { key => headers[key] }
    end
  end
end

Default Headers

The default headers in a Rack test are Cookie and Host.

  it 'returns all headers' do
    get '/api/headers'
    expect(JSON.parse(last_response.body)).to eq(
      'Cookie' => '',
      'Host' => 'example.org'
    )
  end
Kir Shatrov 

Boosting application boot time with container snapshots

Recently I came across the CRIU technology. It lets you checkpoint any running application and serialize its state on disk, to resume it later from that state. What’s more interesting is that it comes with Docker integration, potentially allowing you to run a container, make a serializable snapshot of it and recreate it later - possibly even on another host.

This technology might be beneficial for live migrations (in fact, Google uses it to live migrate batch jobs in Borg) - but what excited me is that this could help with the long boot time problem. As a Rails app grows, it ends up with more Ruby code to parse and load on boot, which makes the startup time quite long. Autoloading and boot…

RubySec 

strong_password Ruby gem malicious version causing Remote Code Execution vulnerability

Appfolio Engineering 

"Wait, Why is System Returning the Wrong Answer?" - A Debugging Story, and a Deep Dive into Kernel#system

I had a fun bug the other day - it involved a merry chase, many fine wrong answers, a disagreement across platforms… And I thought it was a Ruby bug, but it wasn’t. Instead it’s one of those not-a-bugs you just have to keep in mind as you develop.

And since it’s a non-bug that’s hard to find and hard to catch, perhaps you’d like to hear about it?

So… What Happened?

Old-timers may instantly recognize this problem, but I didn’t. This is one of several ways it can manifest.

I had written some benchmarking code on my Mac, I was running it on Linux, and a particular part of it was misbehaving. Specifically, I was using curl to see if the URL was available - if a server was running and accepting…

Notes to self 

Testing Phoenix custom error pages

A short post on using assert_error_sent to test custom error responses on status code, response headers, and body. And when it doesn’t work.

When using Phoenix, we are provided with standard error responses, and so we can just simply test on raises like in the following 404 Not Found example:

assert_raise Ecto.NoResultsError, fn ->
conn
|> using_basic_auth(@username, @password)
|> get(Routes.record_path(conn, :show, record))
end

But it’s better to be a bit more implicit in our intentions when testing a controller:

assert_error_sent 404, fn ->
conn
|> using_basic_auth(@username, @password)
|> get(Routes.record_path(conn, :show, record))
end

assert_error_sent

Awesome Ruby Newsletter 

Issue 163 - Instance Variable Performance

code.dblock.org | tech blog 

Getting Started with Typescript

I’ve done a fair amount of JavaScript, here and there, and have written some TypeScript, too. But I’ve never actually started anything in TypeScript. Attempting a basic “hello world” in TypeScript turned out to be completely non-trivial, so this should help you.

Editor

I use Visual Studio Code.

Node

Setup node.js. I use nvm, whatever recent version of node and npm.

$ node --version
v12.1.0

$ npm --version
6.9.0

Ts-Node

TypeScript comes with an execution and REPL for node.js called ts-node.

$ npm install -g typescript ts-node

$ ts-node --version
v8.3.0

Hello World

Create a file called hello.ts. It’s JavaScript disguised as TypeScript for now.

console.log('hello world');

Run it.

JetRockets 

Deploy AnyCable with Capistrano and systemd

First of all, if you still don't know what is AnyCable than probably you never tried websockets in Rails. "WTF???" you probably will say, and you are right. Yes, we have ActionCable since Rails 5.x, but you really believe Ruby is suitable for real time web? I have bad news for you.
Ruby Weekly 

6 changes coming to Ruby 2.7

#457 — July 4, 2019

Read on the Web

Happy Independence Day to those of you in the United States :-)

Ruby Weekly

6 Changes You Might Have Missed Coming in Ruby 2.7 — Things like Module#const_source_location, FrozenError#receiver and the deprecation of certain, special, Perl-inspired global variables. Also, if you press up in IRB, you’ll be able to bring up an entire method definition in one go, rather than line by line.

Sebastian Sogamoso

'Sorbetting' a Gem, or The Story of the First Adoption — Last week, we featured the release of Sorbet, a type checker for Ruby. This story covers the practicalities of…

Valentino Gagliardi 

Fetch API: Building a Fetch Polyfill From Scratch (For Fun and Promise)

The Fetch API is a browser method for making AJAX requests. Learn how to build your own Fetch API polyfill from scratch and use ES2015 Promises like a pro.

Fetch API: Building a Fetch Polyfill From Scratch

What is the Fetch API?

Often overlooked in favor of libraries like Axios, the Fetch API is a native browser method for making AJAX requests. Fetch was born in 2015, the same year which saw the introduction of ECMAScript 2015 and Promise. But AJAX, a set of technologies for fetching data in the browser exists since 1999.

At that time the ability to fetch data from a web page without causing a page refresh was revolutionary. Nowadays we take AJAX and Fetch for granted but few know that Fetch is nothing more than a…

Code with Jason 

Examples of pointless types of RSpec tests

A reader of mine recently shared with me a GitHub gist called rspec_model_testing_template.rb. He also said to me, “I would like your opinion on the value of the different tests that are specified in the gist. Which ones are necessary and which ones aren’t?”

In this post I’d like to point out which types are RSpec tests I think are pointless to write.

Testing the presence of associations

Here are some examples from the above gist of association tests:

it { expect(profile).to belong_to(:user) }
it { expect(user).to have_one(:profile }
it { expect(classroom).to have_many(:students) }
it { expect(gallery).to accept_nested_attributes_for(:paintings) }

Unless I’m crazy, these sorts of tests…

GoRails Screencasts 

How to send SMS Messages in Rails with Twilio

Sending SMS or Text Messages in Ruby on Rails is really easy using an API like Twilio
Ruby on Rails Podcast 

277: Caching GraphQL with Michael Kelly

Joining Brittany this week is Michael Kelly, a Senior Engineer with Stackshare and a passionate contributor to the open source ecosystem. He is the author of the graphql-cache gem, a caching plugin for graphql-ruby.

Links for this episode:

Brought to you by:

Indeed Prime

  • Indeed Prime is a confidential, free service that puts you in front of leading brands and tech startups with roles you're…
Drivy Engineering 

Things to consider when choosing a third-party API

External third-party-services APIs are useful: they allow you to benefit from the expertise and knowledge that others have acquired on a specific subject - a subject which is not your area of expertise and not the problem in hand. It would take too much time and effort to build and maintain such a service yourself.

However, choosing an API isn’t always an easy task.
Indeed, your choice will have an impact on your codebase and database architecture, and even your service itself. Imagine if your third-party payment-service went down: your customers wouldn’t be able to buy your products.

There are a lot of services that are alike providing APIs, with similar pricing and features.
So, how…

BigBinary Blog 

Rails 6 adds support for Multi Environment credentials

This blog is part of our Rails 6 series. Rails 6.0.0.rc1 was recently released.

In Rails 5.2, encrypted credentails are stored in the file config/credentials.yml.enc. This is a single flat file which is encrypted by the key located in config/master.key.

Rails 5.2 does not support storing credentials of different environments with different encryption keys. If we want environment specific encrypted credentials, we’ll have to follow this workaround.

Rails 6 has added support for Multi Environment credentials. With this change, credentials that belong to different environments can be stored in separate files with their own encryption key.

Let’s see how this works in Rails 6.0.0.beta3

Rail…

RubySec 

Arbitrary Variants Via Query Parameters

RubySec 

Possible arbitrary path traversal and file access via `yard server`

With a Twist 

strong_password v0.0.7 rubygem hijacked

I recently updated minor and patch versions of the gems our Rails app uses. We want to keep dependencies fresh, bugs fixed, security vulnerabilities addressed while maintaining a high chance of backward compatibility with our codebase. In all, it was 25 gems we’d upgrade.

I went line by line linking to each library’s changeset. This due diligence never reported significant surprises to me, until this time. Most gems have a CHANGELOG.md file that describes the changes in each version. Some do not, and I had to compare by git tags or commits list (like cocoon or bcrypt gems). The jquery-rails upgrade contains a jQuery.js upgrade, so the related log was in another project.

And I couldn’t…

Jekyll • Simple, blog-aware, static sites 

Jekyll 3.8.6 Released

We have another patch release in the 3.8 series! This time, we have one security patch and a handful of bug patches, including:

  • Filter symlinks from theme gems
  • Fix excerpt handling of some Liquid tags
  • Handle case where a theme directory doesn’t exist
  • A few internal optimizations to reduce memory overhead

… and a few more! You can check out the patches and see all the details in the release notes

Happy Jekylling!

Honeybadger Developer Blog 

How To Track Timeouts In Honeybadger

The other day a long-time customer wrote in with a problem. They use Honeybadger to monitor their Ruby apps for exceptions but were having trouble catching timeouts. If their app took too long to respond, their application server, Puma, would abort the request. The only insight their team had into this problem was through Puma's logs.

Most people consider timeouts to be a kind of error, so it'd be nice to have them reported by Honeybadger like any other errors. This article will show you how to set that up.

What are timeouts?

When a user requests a webpage, and your app doesn't respond in time, the infrastructure that serves your app assumes something went wrong and kills the request.…

Ruby Magic by AppSignal 

Brewing our own Template Lexer in Ruby

Put on your scuba diving suite and pack your stencils, we’re diving into Templates today!

Most software that renders web pages or generates emails uses templating to embed variable data into text documents. The main structure of the document is often set up in a static template with placeholders for the data. The variable data, like user names or web page contents, replace the placeholders while rendering the page.

For our dive into templating, we’ll implement a subset of Mustache, a templating language that’s available in many programming languages. In this episode, we’ll investigate different ways of templating. We’ll start out looking at string concatenation, and end up writing our own…

All Ruby Podcasts by Devchat.tv 

RR 419: Microservices and Storyscript with Steve Peak

Sponsors

Panel

  • Charles Max Wood

  • Dave Kimura

  • Andrew Mason

With Special Guest: Steve Peak

Episode Summary

Today’s guest Steve Peak has been an entrepreneur and developer for a decade specializing in building tools. He built the company Codecov, one of the top performers in the github ecosystem. His next project is Storyscript, first and only top level programming language that focuses on business logic. The panel begins by discussing what a microservice is and what makes a good one. One of the difficulties with microservices that there is no standardization, and…

All Ruby Podcasts by Devchat.tv 

MRS 092: Leonardo Tegon

Sponsors

  • Sentry use the code “devchat” for 2 months free on Sentry small plan

  • CacheFly

Host: Charles Max Wood

Joined By Special Guest: Leonardo Tegon

Episode Summary

Leonardo Tegon is a software developer at Plataformatec, the company that created the Elixir Language. Leonardo talks about how he ended up at Plataformatec.

Links

Picks

Leonardo Tegon:

Charles Max Wood:

The Bike Shed 

204: I Don't Like Rest

In this week's episode, Steph and Chris discuss ways to unplug and protect personal downtime, RESTful sorting, altering production data within a Rails migration vs a rake task, adopting Unicode characters, and respond to a listener's question about how they approach client relationships and share thoughtbot's Agile-like process.

Test Double | Our Blog 

Imposter syndrome is a jerk.

Recently, I was fortunate enough to attend Ops-Conf, an amazing conference with a group of extremely smart and capable leaders of small tech companies. It hit me pretty quickly that these folks were exceptional people with valuable skills and insights. My first thought was, "Wow, this is awesome!" But then, imposter syndrome walked in and got comfy.

Suddenly "I don't belong here," dominated my thoughts. What business did I have among these people? What could I say or do to keep them from figuring out what I already knew? I needed to calm down fast. Maybe they could forgive me for being naive and awkward, but I could never show my face again if I had an emotional breakdown in front of…

Ruby Together News 

Career Switching Into Code

Career Switching Into Code

She thought politics was her future, turns out it was programming.

Ruby Me Apprentice Alicia

Alicia envisioned a future in politics. The California native studied political science and anthropology in college and then made the move to Washington DC to pursue a career on The Hill. After a few jobs—with a think tank, a bank, and an NGO—she learned of an opportunity thanks to Women Who Code DC, where other women her age or younger were problem-solving and gaining financial independence through careers in software development.

Ready for the career change, Alicia dropped everything, enlisted in a coding bootcamp, moved from DC to Atlanta, and started her dedicated journey into programming.…

Julia Evans 

Get your work recognized: write a brag document

There’s this idea that, if you do great work at your job, people will (or should!) automatically recognize that work and reward you for it with promotions / increased pay. In practice, it’s often more complicated than that – some kinds of important work are more visible/memorable than others. It’s frustrating to have done something really important and later realize that you didn’t get rewarded for it just because the people making the decision didn’t understand or remember what you did. So I want to talk about a tactic that I and lots of people I work with have used!

This blog post isn’t just about being promoted or getting raises though. The ideas here have actually been more useful to…

RubyGuides 

Read This If You Want to Understand Instance Variables in Ruby

If you want to learn about instance variables, how they work & why they’re useful.

You’re in the right place!

First question…

What’s an instance variable?

In the Ruby programming language, an instance variable is a type of variable which starts with an @ symbol.

Example:

@fruit

An instance variable is used as part of Object-Oriented Programming (OOP) to give objects their own private space to store data.

We say that objects can:

  1. Do things
  2. Know things

Methods make things happen, they DO things.

Instance variables store data, they KNOW things.

Example:

If you have a Fruit class, you may want to know what kind of fruit it’s, what color, weight, etc.

All of these attributes become instance…

Riding Rails 

☀️🏖🏄‍♀️ and schema cache deduplication plus getutc begone

Ahoy all! 🚢 Step aboard as we cruise through the Rails news this week. Summer has really hit its simmering point for many a Rails contributor: we’re seeing fewer contributions. Take heed! Your trusty captain Kasper is here to reassure you that nothing has gone wrong on this ship and that it’s merely summer time seasoning. But also, the engine is on fire? Oh well, it’ll probably burn out soon enough and another wrong has been righted! This is fine. 🔥

Schema Cache: deduplicate structures

This week has primarily been a strong one for Active Record’s schema cache with no less than 3 improvements. It’s a little known feature but it avoids querying your database for its schema every time a new…

JetRockets 

What is MVP and why it is crucial to product success.

What does MVP stand for? What are the benefits of developing an MVP? How do I go about it? - these are just few questions that we get asked often by prospective clients. We have decided to write an article that answers these questions and offers a few tips on how to go about developing a successful MVP.
Remote Ruby 

Join by Daniel Pritchett

RubyMine Blog 

Debugging in RubyMine

One of the main advantages of IDEs over text editors is the debugging experience. In this blog post, we’ll review the rich debugging capabilities available in RubyMine and then we’ll have a quick rundown of the new debugging features added in v2019.2. These include performance optimizations, Smart Step Into, block breakpoints, and others.

The RubyMine debugger provides various ways to examine the state of a running application: you can step through your code and check variable values, set watches on variables to see when values change, and so on. All of these features are applied to Ruby projects and Rails applications. You can debug everything from .rb scripts to .erb and .haml views.

Let…

Awesome Ruby Newsletter 

Issue 162 - Sorbetting a gem, or the story of the first adoption

Cognito Blog 

3 Reasons Why It’s Time To Upgrade Your IDV Solution

2019 Identity Verification Trends

As humans, we are always longing for the latest and greatest; an upgraded car, the latest iPhone version or a first class upgrade on our next flight. We long for these upgrades because we know they offer enhancements that will ultimately make our lives easier and better. While it may not be as top of mind as a new phone, the same can be said for your company’s IDV solution. You, your CEO, investors, and your customers will all benefit from a state of the art, upgraded IDV solution.

You will have less headache working with a battle tested API, your management will be amazed by the increased user volume, investors will love increased profits from a cost effective solution and customers…

Honeybadger Developer Blog 

PagerDuty Integration Reborn

Why did we update our PagerDuty integration?

We had one of our awesome customers reach out to us regarding our PagerDuty integration and how it could be made more awesome for them. Our co-founder Josh's eyes grew wide with excitement, so he immediately went to work on improving the integration. He even broke the golden rule of coding and...deployed. On. A. Friday! (gasp)

What does Honeybadger’s PagerDuty integration do?

Combining Honeybadger with PagerDuty allows you distribute all uptime, check-in, and error reporting alerts to your team so you can fix problems in record time.

Ok, that great but it sounds like what the integration has always done. What’s new?

We are getting there,…

Ruby Weekly 

Ruby gets a fast, powerful type checker

#456 — June 27, 2019

Read on the Web

Ruby Weekly

Sorbet – A Fast, Powerful Type Checker for Ruby – is Now Open Source — Stripe have been working on a type-checker for Ruby for quite some time now and it’s now publicly available and open source after undergoing rigorous testing at 30 companies. (Psst.. if you write up any good Sorbet related blog posts, let us know, we want to link to them!)

Sorbet

A Look at Instance Variable Performance — You know when tenderlove starts a post with “Let’s start today’s post with a weird Ruby benchmark..” you’re in for a fun read and will learn how the order in which you…

Aaron…

The Miners - Medium 

What a flerken are React PropTypes and how to use them in a fancy way?

One of the main concepts of a React Component is its props. The props are used to pass data to a component, just like a parameter is to a function, with the difference that when the data changes, the component that receives the prop re-renders automatically. They can become a problem when you have a large project with a lot of components because you will probably forget the type of each prop, and when someone else needs to change or use this code they will definitely be lost. One solution for that is to use the components propTypes property.

What are propTypes?

The propTypesis an attribute of React components that allows validating the types of the component props (pretty intuitive hm?). So…

OmbuLabs Blog 

Contributing To Open Source

Contributing to open source might be scary, you might think that your pull request (PR) is not good enough; that people will judge you by your code; or that fixing that little typo is not worth it.

I had all these questions in my head before I submitted my first contribution to an open source project and it stopped me many times.

So my suggestion is: start small. Look for low hanging issues in a project you want to contribute to; start reviewing issues; and see if they have been solved in the past. Then you can suggest a fix. If you take it one small issue at a time, you will start learning the code base and it will give you the confidence you need to start tackling more complex issues.

BigBinary Blog 

Rails 6 adds before? and after? to Date and Time

This blog is part of our Rails 6 series. Rails 6.0.0.rc1 was recently released.

Rails 6 adds before? and after? to Date , DateTime , Time and ActiveSupport::TimeWithZone classes.

before? and after? are aliases to < (less than) and > (greater than) methods respectively.

Let’s checkout how it works.

Rails 5.2

Let’s try calling before? on a date object in Rails 5.2.

>> Date.new(2019, 3, 31).before?(Date.new(2019, 4, 1))

=> NoMethodError: undefined method 'before?' for Sun, 31 Mar 2019:Date
	from (irb):1

>> Date.new(2019, 3, 31) < Date.new(2019, 4, 1)

=> true

Rails 6.0.0.beta2

Now, let’s compare Date , DateTime , Time and ActiveSupport::TimeWithZone objects using before? and after? i…

>> Date.new(2019, 3, 31).before?(Date.new(20…
Schneems - Programming Practices, Performance, and Pedantry 

Puma 4: New I/O 4 Your Server

Here’s the setup: You are a web server named Puma. You need to accept incoming connections and give them to your thread pool, but before we can get that far, you’ll have to make sure all of the request’s packets have been received so that it’s ready to be passed to a Rack app. This sounds like the job for a Reactor!

Semaphore 

Continuous Deployment of a Python Flask Application with Docker and Semaphore

Docker is a container technology that enables developers to run entire applications as a unit. It offers all the benefits of virtual machines, without the high overhead:

  • Consistency: Production and development environments are equal.
  • Portability: fewer dependencies with the underlying OS; the same image can be deployed on any cloud provider.
  • No overhead: better performance than virtual machines.
  • Divide and conquer: distribute services among different containers.

However, Docker introduces a new variable to the equation: the app must be baked into the container image, then correctly deployed. In addition, setting up a test environment can prove more challenging.

Here is where a CI/CD…

Ruby on Rails Podcast 

276: Introducing ActionView::Component with Joel Hawksley

Joel Hawksley is a software engineer at GitHub. He recently served as the technical lead for Project Paper Cuts, incorporating feedback from the community into GitHub. He is now the lead on introducing support for ActionView::Component into Rails core.

Links for this episode:

Brought to you by:

Hoefler&Co

A good font is one of the best…

Paweł U. | Ruby on Rails Web Development Consultant Full Stack Blog 

How to Backup Heroku Postgres Database to an Encrypted AWS S3 Bucket

Heroku offers a robust backups system for it’s Postgres database plugin. Unfortunately, you can irreversibly lose all your data and backups just by typing a single command. It might seem improbable, but still, I would rather not bet my startup’s existence on a single faulty bash line. In this tutorial, I will describe how to set up a proprietary redundant Heroku PostgreSQL backups system to a secure AWS S3 bucket.

I will be covering various tools including AWS CLI, OpenSSL, GPG, Heroku buildpacks, and scheduler but you don’t need to be familiar with any of those. By following this guide, you will set up a reliable, custom backups system for Heroku PostgreSQL database even if you don’t have…

RubyMine Blog 

YARD support in RubyMine

YARD is a popular Ruby documentation generation tool that is used in multiple libraries for documenting code. RubyMine helps you to work with YARD tags and documentation in various ways, for example, you can view the documentation using Quick Documentation Lookup, create missing YARD tags, and check the validity of a YARD tag. RubyMine can also utilize the YARD annotations for better code insight, it uses them to help suggest more relevant results in code completion and parameter hints for methods.
In this blog post, we’ll remind ourselves about the existing capabilities available in RubyMine for YARD and look at the new ones we’ve added.

View documentation

First…

All Ruby Podcasts by Devchat.tv 

MRS 091: Kurtis Rainbolt-Greene

Sponsors

  • Sentry use the code “devchat” for 2 months free on Sentry small plan
  • CacheFly

Host: Charles Max Wood

Joined By Special Guest: Kurtis Rainbolt-Greene

Episode Summary

Links

Picks

Kurtis Rainbolt-Greene:

Charles Max Wood:

All Ruby Podcasts by Devchat.tv 

RR 418: The Life and Death of a Rails App with Olivier Lacan

Sponsors

Panel

  • Charles Max Wood

  • David Kimura

  • Nate Hopkins

  • Andrew Mason

With Special Guest: Olivier Lacan

Episode Summary

Olivier Lacan joins the panel again. He currently works for Pluralsight. Today they are talking about the spectrum of creating a Rails app, or any app, from the birth of the idea to the death of the project. They stress the importance of planning for updates. Olivier talks about his experience in maintaining Code School, which has now been incorporated into Pluralsight. David also shares his experience with the life and death of a…

The Bike Shed 

203: A Blessed Monkeypatch (Eileen M. Uchitelle)

On this week's episode, we revisit RailsConf 2019 for another live recording, this time with Eileen M. Uchitelle, GitHubber and rails core team member. Eileen joins Chris to discuss her RailsConf talk on how GitHub maintained a custom fork of Rails for years, how they finally moved off it, and what lessons we can take away from their experience. They also discussed Eileen's recent work on automatic database switching coming in Rails 6, microservices and monoliths, and getting into working on Rails.

This episode of The Bike Shed is sponsored by Indeed Prime

Test Double | Our Blog 

Things I Wish I Knew Before Going Remote

The video above was recorded at RailsConf 2019 in Minneapolis, Minnesota.

Remote work is just like working in an office—minus the soul-crushing commute. How hard could it be?

Spoiler: it's actually pretty hard.

When I went remote, I was so excited to not pack a lunch that I didn't consider the implications of a quasi-reliable Internet connection or the psychological impact of spending so much time at home.

As it turns out, going remote isn't just trading a highway commute for a hallway one. It requires new skills and a mindset shift. In this talk, you'll learn how to assess your needs as a remote worker and gain a set of tools to help you succeed for the long term.

If you liked this talk,…

RubyGuides 

How to Use The Ruby Begin & Rescue Keywords (With Examples)

Let’s talk about the begin keyword in Ruby.

What is it?

First, you need to understand something.

Your Ruby programs may trigger an error state at multiple points while they’re running.

Examples include:

  • You’re trying to read a non-existing file
  • You divide a number by zero
  • A web server you’re working with has an outdated SSL certificate

When that happens…

Ruby doesn’t crash right away!

You get a chance to handle & recover from the error.

We call this “exception handling”.

Ruby gives you a few keywords to implement error recovery in your code.

These keywords are begin & rescue.

Let’s discover how to use them!

How to Handle Ruby Exceptions

How do you handle these exceptions?

You can wrap the…

BigBinary Blog 

Rails 6 adds Array#extract!

This blog is part of our Rails 6 series. Rails 6.0.0.rc1 was recently released.

Rails 6 added extract! on Array class. extract! removes and returns the elements for which the given block returns true.

extract! is different from reject! in the way that reject! returns the array after removing the elements whereas extract! returns removed elements from the array.

Let’s checkout how it works.

Rails 6.0.0.beta2

Let’s pluck all the user emails and then extract emails which include gmail.com.

>> emails = User.pluck(:email)
SELECT "users"."email" FROM "users"

=> ["amit.choudhary@bigbinary.com", "amit@gmail.com", "mark@gmail.com", "sam@gmail.com"]

>> emails.extract! { |email| email.include?(
Semaphore 

Steve Peak from Storyscript on the future of software development and creating a new language focused on data flow

We invite software industry professionals to Semaphore Uncut YouTube show to discuss what problems they’re currently solving and what excites them about the emerging technologies.

In this episode, we were chatting with Steve Peak, Founder & CEO at Storyscript.

This chat was recorded on June 5th, 2019 and is also available in the form of a podcast.

Full transcription below.

Darko [00:11:23] Welcome to Semaphore Uncut, a place where we talk about cutting edge technologies and people who build them. My name is Darko. I’m your host for today, and with us we have Steve Peak. Steve, please go ahead and introduce yourself.

Steve [00:11:39] Hi. Thank you, Darko, for having me…

Julia Evans 

What does debugging a program look like?

I was debugging with a friend who’s a relatively new programmer yesterday, and showed them a few debugging tips. Then I was thinking about how to teach debugging this morning, and mentioned on Twitter that I’d never seen a really good guide to debugging your code. (there are a ton of really great replies by Anne Ogborn to that tweet if you are interested in debugging tips)

As usual, I got a lot of helpful answers and now I have a few ideas about how to teach debugging skills / describe the process of debugging.

a couple of debugging resources

I was hoping for more links to debugging books/guides, but here are the 2 recommendations I got:

“Debugging” by David Agans: Several people…

Karol Galanciak - Ruby on Rails and Ember.js consultant 

Messages on Rails Part 3: RabbitMQ

In the first part of this series, we were exploring some potential options for communication between services – what their advantages and disadvantages are, why HTTP API is not necessarily the best possible choice and suggesting that asynchronous messaging might be a better solution, using, e.g. RabbitMQ and Kafka. We’ve already covered Kafka in the part 2, now it’s the time for RabbitMQ.

What is RabbitMQ, and how does it work?

RabbitMQ is a general purpose message broker supporting multiple protocols, yet, we are going to focus mostly on AMQP, which is the one that is the most typically used. It implements a smart broker/dumb consumer model. Unlike Kafka, it means that the broker is…

Notes to self 

Automating tasks and improving developer workflow with pre-commit git hooks

Probably the most usual git workflow is adding changes to the staging area, committing them, and pushing them to the remote repository. Depending on the project we are working on there are some things that we should be checking, validating or generating before heading for the commit. That’s where pre-commit hooks come in.

What’s pre-commit hook? Git has various checkpoints that we can hook into by providing an executable in .git/hooks/ with the name of the hook. One of them is the pre-commit hook that is ran automatically by git before commiting changes to the repository. If we want git to run arbitrary code before each and every commit we simply create .git/hooks/pre-commit

avdi.codes 

Tools for turning descriptions into diagrams

Sometimes I have a picture of a software design in my head and I just want to draw it. If I don't need to collaborate with anyone remotely I might just draw it freehand. For collaborations and for diagrams I might want to iterate on, a tool like LucidChart can be really handy.

But sometimes I just want to list concepts as I hear them, fill in the connections between them, and let a computer worry about layout. That's what the tools below are all about. The particulars of each tool differ, but all of them let you enter a simple text description, e.g.:

[Chili]-->[Beans]
[Chili]-->[Tomatoes]
[Chili]-->[Onions]

And they will turn it into a visual diagram, like so:

A diagram of chili ingredients

(This diagram was generated…

Appfolio Engineering 

Why is Ruby Slower on Mac? An Early Investigation

Sam Saffron has been investigating Discourse test run times on different platforms. While he laments spending so much extra time by running Windows, what strikes me most is the extra time on Mac — which many, many Rubyists use as their daily driver.

So which bits are slow? This is just a preliminary investigation, and I’m sure I’ll do more looking into it. But at first blush, what seems slow?

I’m curious for multiple reasons. One: is Mac is so slow, is it better to run under Docker, or with an external VM, rather than the Mac? Two: why is it slow? Can we characterize what is so slow and either do less of it or fix it?

First, let’s look at some tools and what they can or can’t tell us.

Ruby-Prof

avdi.codes 

How to relax your Ruby version specification in your Gemfile

Have you ever run into this error?

Your Ruby version is 2.6.1, but your Gemfile specified 2.6.3

Annoying, right? You know your Ruby version is new enough to run this application, but the Gemfile is so fussy.

Turns out, Gemfiles don't have to be so picky. Just like you can relax version dependencies for gems, you can also make your Ruby version specifier less specific. As with gems, the secret is using the tiddly-waka (~>) operator:

ruby '~> 2.6.0'

Now this project will run with any patch version of Ruby 2.6 without complaint.

Awesome Ruby Newsletter 

Issue 161 - I'm worried about Ruby future

Ruby Weekly 

A production-optimized alternative distribution of MRI

#455 — June 20, 2019

Read on the Web

Ruby Weekly

▶  Progress on Compacting GC in Ruby 2.7 — No, this is not a short talk (indeed, it’s an hour long, but the actual technical part starts at 15 minutes in) but Aaron, both a member of the Ruby and Rails core teams, explains what work is taking place to improve Ruby’s garbage collector by essentially ‘defragging’ (or ‘compacting’) the memory that Ruby uses at runtime.

Aaron Patterson

Fullstaq Ruby: An Alternative CRuby Distribution, Optimized for Production — A CRuby/MRI-based Ruby distribution that’s optimized for production environments out of the box,…

Hongli…

Drifting Ruby Screencasts 

Teaching at Bootcamps with Ed Toro

Ed Toro speaks to his experience at bootcamps from a teacher's perspective. We gain a different perspective of what bootcamps are like. Ed shares valuable information whether you're considering getting into coding or currently at a bootcamp.
Ruby on Rails Podcast 

275: ITP 2.1, Github is on Fire and Mechanical Keyboards with Brittany & Nick

Nick Schwaderer and Brittany Martin talk about all of the cool things that are happening in their worlds. Tune in to dive into robots, the great cookie debate, Github acquisitions and new features and, of course, keyboards.

Links for this episode:

Brought to you by:

Whether you…

Semaphore 

Python Continuous Integration and Deployment From Scratch

Python is the oldie-but-goodie of programming languages. Since the ’80s, it has provided developers with reliability and ease-of-use.

No matter how reliable your coding language is, however, you need to implement continuous integration and delivery (CI/CD) to detect and remedy errors quickly. When you have confidence in the accuracy of your code, you can ship updates faster and with fewer mistakes.

By the end of this hands-on guide, you’ll understand how to build, test and deploy a Python website. We’ll then show you how to use a continuous integration and delivery platform, Semaphore, to automate the whole process. The final CI/CD pipeline will look like this:

What we’re…