Rubyland

news, opinion, tutorials, about ruby, aggregated
Sources About
Ruby Open Data Week 2021, March 6th to March 12th - 7 Days of Ruby (Open Data) Gems 

Day 2 - beerdb Gem - Serve a Guinness Irish Stout or a Bamberg Aecht Schlenkerla Rauchbier Märzen as JSON - Free Home Delivery

Written by Gerald Bauer A code monkey and enthusiastic collector (and publisher) of open football and beer data. Skills include Ruby, SQLite and CSV. Spec lead of CSV <3 JSON. What’s the beerdb gem? The beerdb gem offers a ready-to-use database schema (in SQL) and models such as - surprise, surprise - Beer, Brewery, Brand and friends (using the ActiveRecord object-relational mapper machinery). Example: Let’s try the brewery model: by = Brewery.find_by( key: 'guinness' ) by.title #=> 'St. James's Gate Brewery / Guinness Brewery' by.country.key #=> 'ie' by.country.title #=> 'Ireland' by.city.title #=> 'Dublin' by.beers.first #=> 'Guinness', 4.2 ... Or let’s try the beer…
Engine Yard Blog 

A Discussion with Clare Liguori from AWS Container Services

Steam Powered - a Podcast from Engine Yard

Steam Powered is a podcast from the folks at Engine Yard where we talk about all things Cloud, Kubernetes, IaaS, Paas, Ruby, and what's new in the world of development.

AkitaOnRails.com 

[Akitando] #93 - Hello World Como Você Nunca Viu! | Entendendo C

DESCRIÇÃO

Se você nunca viu C ou como um programa funciona de verdade no baixo nível, hoje é sua chance de ver todo o básico de uma só vez!

Vou desde tipos primitivos, strings, arrays, stacks, heap, alocação de memória, structs, até minimamente entender o que está por baixo do que você chama de linguagem "orientada a objetos".

ERRATAS

  • em 00:06:50 falei errado o range de INT, o certo é de -128 a 127
  • em 00:06:06 eu falei certo e deixei a correção escrita errada. 64 bits, se você não precisar, desperdiça 7 bytes
  • em 00:40:54 eu falei que 255 bytes é 1/4 de 1 megabyte, mas é de 1 KILObyte.
  • em 00:45:41 eu coloquei hello no sizeof e ele pegou o sizeof do endereço e não do array.
  • em…
Ruby Open Data Week 2021, March 6th to March 12th - 7 Days of Ruby (Open Data) Gems 

Day 1 - factbook Gem - Turn the World Factbook into Open Structured Data (e.g JSON) - Free Intelligence on the History, People, Government, Economy, Energy, Geography, Communications, Transportation, Military 'n' Terrorism for 260+ Countries

Written by Gerald Bauer A code monkey and enthusiastic collector (and publisher) of open football and beer data. Skills include Ruby, SQLite and CSV. Spec lead of CSV <3 JSON. Let’s start with a trivia quiz: Q: What country has the biggest stock of proved reserves¹ of crude oil in barrels (bbl) - according to the Central Intelligence Agency (CIA)? (A) Canada (B) Iraq (C) Iran (D) Saudi Arabia (E) Venezuela (F) Other, please tell! ¹: Proved reserves are those quantities of petroleum which, by analysis of geological and engineering data, can be estimated with a high degree of confidence to be commercially recoverable from a given date forward, from known reservoirs and…
John Nunemaker 

Resilience in Ruby: Shell Commands

This post is half a gentle nudge that you should be using GitHub::Result more often and half a continuation of my Resilience in Ruby and Limit Everything: Timeouts for Shell Commands in Ruby posts. You can read this post and get value without reading those, but if you really want to dig in, I'd read them first.

Adding timeouts to Speaker Deck's shell commands (as discussed in the aforementioned limit everything post) was a great start. But that wasn't enough. The code was not re-usable and definitely not aesthetically pleasing.

Last night I watched Semicolon & Sons Rails Best Practices video (it's great, you should watch it). One note that stuck with me was:

Programmers like me who work on a…
OmbuLabs Blog 

How to Pitch a Maintenance Project to Your (Non-Technical) boss

The impact of technical debt is obvious to developers. Devs are the ones that have to tackle the headaches of dependency issues and patch holes in the security.

But the reasons for performing software maintenance can get lost in translation when they’re discussed with non-technical executives. It can be unclear how rewriting functioning code can translate into more money in the bank and why it’s worth dedicating time to.

So, here’s how we describe the business reasons to prioritize your maintenance.

Technical Debt = unserviced equipment

In general, technical debt is like a restaurant not taking care of its kitchen.

You’ll be providing customers with the same food and experience at…

Remote Ruby 

Building a Business on Rails with Mike Perham

[00:01:40] Mike tells us about himself, what he was doing before he started Sidekiq, and what led in the idea of him starting it.
[00:03:46] Jason asks Mike if he thinks a lot of thread safe code in our ecosystem came from just people adopting Sidekiq, and when he started Sidekiq did he have plans of it becoming paid tiers or was it purely an open source project at the time.
[00:06:07] When he moved to the open core model, Mike tells us if he had both the pro and enterprise license at one time or if it was there just one license. [00:08:35] Jason asks Mike when you’re searching for things about Sidekiq, and you see other libraries that aren’t from Sidekiq, but they’re Sidekiq dash…
Planet Argon Blog 

Developing Client Communication Skills as an Engineer

Developing Client Communication Skills as an Engineer

Good communication with clients involves asking questions, especially asking the right questions. Here are lessons from my internship at Planet Argon about effective communication with clients.

Continue Reading

Awesome Ruby Newsletter 

💎 Issue 250 - Inside Gemfile - intense dive in to see how bundle install command works under the hood

Test Double | Our Blog 

Announcing Standard Ruby 1.0

One of the open source projects Test Double maintains is called Standard Ruby. No, it’s not Ruby’s standard library and it doesn’t implement any industry standards. Instead, Standard—like the JavaScript library of the same name—is a set of static analysis (“linting”) and code style rules for your Ruby code.
Ruby Weekly 

Five ways to make HTTP requests from Ruby

#542 — March 4, 2021

Read on the Web

💡 We've had some fantastic Tip of the Week feedback, so we're carrying on :-) If you have any suggestions of things Jemma could cover, you can tweet her @jemmaissroff — she's also keeping a Twitter thread of quick Ruby tips if you want even more.
__
Peter Cooper, editor

Ruby Weekly

Upgrow: A Sustainable Architecture for Rails Apps? — Spotify draws on its experience as a Rails shop to create this guide with patterns (and anti-patterns) for creating large, long-lived Rails apps. Do you agree with their choices?

Spotify

Standard 1.0: A Ruby Style…

Boring Rails: Skip the bullshit and ship fast |  

Find records missing an association with `where.missing`

You can’t prove a negative, but what about querying a database for a negative? While the majority of the time you are writing queries to find data, there are some cases when you want the opposite: writing a query that looks for the absence of data.

When it comes to raw SQL, you can use a LEFT OUTER JOIN combined with a NULL check to find records without certain associations.

Usage

In Rails, you can apply the same concepts from SQL directly with ActiveRecord.

Let’s say you have the following model:

class Account < ApplicationRecord
  has_many :recovery_email_addresses
end

If you wanted to find Accounts that have not yet set up a backup recovery email, you could write this query and…

Planet Argon Blog 

Preparing to Ask: An Intern’s Guide to Questions

Preparing to Ask: An Intern’s Guide to Questions

Asking questions is a key part of learning in any role, including an engineering internship. Here are some steps on when and how to ask the best questions.

Continue Reading

Code with Jason 

Active Record queries in views: when it’s bad, when it’s fine

“No Active Record queries in views”

Maybe you’ve heard the advice that you shouldn’t put Active Record queries (or other logic) in views, but you’re not sure exactly why, other than “separation of concerns”. Why exactly is separation of concerns good?

The rationale behind this advice is that mixing concerns (like query logic vs. presentation) makes the code harder to understand and change.

Another way to think about this is to think about what kinds of things tend to change together.

Related changes

Even though many changes require touches at multiple levels in order for the change to be complete (model, controller, view)​, some changes are more closely related than others.

A change to the…

JRuby.org News 

JRuby 9.2.16.0 Released

The JRuby community is pleased to announce the release of JRuby 9.2.16.0

JRuby 9.2.x is compatible with Ruby 2.5.x and stays in sync with C Ruby. As always there is a mix of miscellaneous fixes so be sure to read the issue list below. All users are encouraged to upgrade.

As we are still actively working on 9.3.0.0 we decided to put out another 9.2.x release to fix some of the more recently reported issues.

Compatibility

  • Fixed an issue in Kernel#system where subprocesses that daemonize would cause waitpid to hang. (#6579, #6582)

Standard Library

  • Elevated the racc library to a default gem, so it…
Rails with Jason 

085 - Systematic Debugging with Matt Swanson

In this episode I talk with Matt Swanson about how to debug systematically rather than haphazardly.

Links:

OmbuLabs Blog 

Nested Forms in Rails

Have you ever had to deal with complex forms creating multiple objects and hierarchies in one request? Rails is there to help provide a set of helpers, methods and conventions to build nested forms, handle assignment, and creation of the objects involved in only a few lines of code. In this blog I'll explain how that works using accepts_nested_attributes_for, fields_for, strong parameters and more.

The Convention

Let's start with the parameters Rails expects in the request. Suppose we have this object and relationships: a Person has one Address and has many Pets.

We would have these models:

class Person < ApplicationRecord
  has_one :address
  has_many :pets
end

class Address < Applic…
Ruby on Rails Podcast 

360: Diffend, Security and Running with Ruby with Maciej Mensfeld

Maciej Mensfeld is a Software Architect with experience in a wide variety of business applications built using multiple Ruby frameworks. He is particularly interested in code quality assurance and OSS supply chain security. He is an active OSS contributor and maintainer of various projects including Karafka and Diffend.

Links for this episode:

Brought to you by:

ExpressVPN

ExpressVPN is an app that reroutes your internet connection through their secure servers so your ISP can’t see the sites you visit.

If you visit https://EXPRESSVPN.com/RUBY right now, you can get an extra three months of ExpressVPN for free! Support the show and protect…

RubyGems Blog 

3.2.13 Released

RubyGems 3.2.13 includes bug fixes.

To update to the latest RubyGems you can run:

gem update --system

To install RubyGems by hand see the Download RubyGems page.

## Bug fixes:

  • Support non-gnu libc linux platforms. Pull request #4082 by lloeki

SHA256 Checksums:

  • rubygems-3.2.13.tgz
    6b8b2666f068dbaca376da794b767a9b2c37d8f30b09b612931ff938c8471403
  • rubygems-3.2.13.zip
    4164507064e5a56f9162a2d80a86a7dfa8d1882a2cb9a2f764edc611ee6c87d6
  • rubygems-update-3.2.13.gem
    6afba2d705a6c9c3a58486c4d7f24c90a2342d8bc9308018a2b74588fee8a77a
Greater Than Code 

224: Better Allies with Karen Catlin

02:31 - Karen’s Superpower: The Ability to Simplify Things

  • Simplifying in a Team Context

05:55 - Better Allies – Everyday Actions to Create Inclusive, Engaging Workplaces; Triaging and Curating Research

14:15 - Maintaining Anonyminity (at first); Prove It Again Bias

26:09 - Culture Add + Values Fit

32:11 - Network…

All Ruby Podcasts by Devchat.tv 

RUBY 488: The Road to Ruby 3 - Part 1 - Ruby 2.6 to Ruby 2.7

In this episode, John, Luke, and Chuck begin the discussion on Ruby 3.0's release by discussing the differences and enhancements in Ruby 2.7 over version 2.6. Luke leads the charge in providing a list of the differences and the Rogues debate the merits of the various changes in the last minor release of Ruby 2 before releasing Ruby 3.0.

Panel

  • Charles Max Wood
  • John Epperson
  • Luke Stutters

Sponsors

Picks

Julia Evans 

Things your manager might not know

When people talk about “managing up”, sometimes it’s framed as a bad thing – massaging the ego of people in charge so that they treat you well.

In my experience, managing up is usually a lot more practical. Your manager doesn’t (and can’t!) know every single detail about what you do in your job, and being aware of what they might not know and giving them the information they need to do their job well makes everyone’s job a lot easier.

Here are the facts your manager might not know about you and your team that we’ll cover in this post:

  • What’s slowing the team down
  • Exactly what individual people on the team are working on
  • Where the technical debt is
  • How to help you get better at your job

For each…

Boring Rails: Skip the bullshit and ship fast |  

Testing multiple sessions in the same test with Capybara

Sometimes a feature in your application will involve a back-and-forth between multiple users. When it comes time to write an automated system test, you can easily simulate switching between users using Capybara’s using_session helper.

Instead of logging in and out or faking out another user making changes to the app, you can use multiple sessions within the same Capybara test.

This can be very useful for testing features like notifications, chat, or even multi-person workflows where different users have to take action to move a process forward.

Usage

There are a few options for controlling the session in Capybara.

You can set the session manually:

Capybara.session_name = "Test session…

But I prefer…

Rebased Blog 

Redis rate limiter – part 2

Welcome to part 2, where we’ll take a look at how to test the rate limiter. First of all we have to make a couple changes to the class we’ve created in part 1. The first change is to make the interval and timeout instance variables configurable during initialization. This...
EquiValent 

Publicly accessible Elasticsearch 7.x

how to expose ElasticSearch on a VM globaly (public access)

or: How to access ElasticSearch 7.x installed on a VM from my laptop

note this is a terrible idea! don’t do this for production ES. This is only usefull for debugging or if you have strong firewall setup

Edit file /etc/elasticsearch/elasticsearch.yml to values:

network.host: 0.0.0.0
network.bind_host: 0.0.0.0
network.publish_host: 0.0.0.0


discovery.seed_hosts: ["0.0.0.0", "[::0]"]

and restart elasticsearch sudo service elasticsearch stop + ... start

source https://stackoverflow.com/a/65718115/473040

BigBinary Blog 

Rails 6.1 adds ActiveRecord::FinderMethods 'sole' and 'find_sole_by'

<br/>

Before Rails 6.1

There were no methods defined to find and assert the presence ofexactly one record at the same time.

For example, we have a class Product with a price field and we want to find asingle product that has a price of 100. For zero or multiple productswith the price of 100, we want to raise an error. We can not add databaseconstraints to make a unique field of price.

Now to solve the above query, we don't have any method defined inActiveRecord::FinderMethods module. We can find a product with the given priceor raise an error if no record is found using the queries mentioned in the belowexample.

Product.find_by!(price: price)#=> ActiveRecord::RecordNotFound Exception     (if no…
Long live Ruby 

Inside Gemfile - intense dive in

Gemfile is a well-known file even for not experienced Ruby developers. While for most people, it’s evident that the purpose of that file and the bundler library, fewer of them know how bundler works and what happens from the time you declare the gem in the Gemfile to the moment when it is installed in your system. It is time for another deep dive into Ruby’s code internals to see how the Gemfile works with bundler
Josh Software 

Spring Boot Actuator- Web application monitoring made easy !!!!

Contents What is spring boot actuator? Enable actuator in spring boot application What are actuator endpoints? Enabling spring boot actuator endpoints Actuator metrics endpoint What is spring boot actuator? Spring boot actuator module provides you the features which will help you monitor and manage your application. You can monitor your application status, gather various statistics … Continue reading Spring Boot Actuator- Web application monitoring made easy !!!!
Saeloun Blog 

React 17 stops event bubbling in scroll event

React bubbled all its events before React 17, even the ones that the browser doesn’t bubble by default. This has caused some weird behavior #19156 #15723 with scroll event.

To demonstrate one of the issues let’s take a simple example.

A scrollable div containing some text is wrapped by parent div. The parent div has onScroll event attached to it which changes the background color to pink.

class App extends React.Component {
  parentNode = React.createRef();

  handleScroll = (e) => {
    if (!ticking) {
      window.requestAnimationFrame(() => {
        //Change background color to pink
        this.parentNode.current.style.background = '#E22C7E';
        ticking = false;
      });
The Bike Shed 

283: Who's The User?

On this week's episode Steph and Chris discuss a listener question around managing content within an application, weighing options like an integrated CMS, headless CMS provides, proxying the content, and supporting marketing and landing pages without needing a developer for every change. They also provide an update on dead man's snitch and a preview of a rails 6 upgrade on the horizon and dreams of database switching.


This episode is brought to you by SPOTcon. Tune in to Scout APM's first conference, and join for developers from around the world to meet, engage with, and learn about solutions that drive leading-edge transformation in application development by registering for…

Engine Yard Blog 

The Ruby Unbundled Series: Creating Games with Gosu

There are literally so many treasures in Ruby (specifically avoiding the cliche pun on ‘gem’ here), that it is sometimes hard to choose where to go next for each article. When I started writing this last Friday, I felt like switching gears to something fun, games. This is a topic that likely sparked interest in computers for many of you in the first place.

Test Double | Our Blog 

Why privacy-minded analytics can fix marketing

How did things get so off-track when it comes to data privacy? Especially in marketing and advertising. The answer ties into why Test Double is choosing privacy-minded analytics for our website.
Mike Perham 

Faktory News: Pause, RSS and Bring your own Redis

Faktory is my background job server for use with any programming language. It brings the nice patterns and features available in Sidekiq to the rest of the world. Using Go, Python, JavaScript, Elixir, or other languages? Give Faktory a shot! Today I’ve released Faktory, Faktory Pro and Faktory Enterprise 1.5.0. What’s new? Pause / Resume The OSS version of Faktory now allows you to Pause and Resume processing for a queue.
RubyGems Blog 

3.2.12 Released

RubyGems 3.2.12 includes bug fixes.

To update to the latest RubyGems you can run:

gem update --system

To install RubyGems by hand see the Download RubyGems page.

## Bug fixes:

  • Restore the ability to manually install extension gems. Pull request #4384 by cfis

SHA256 Checksums:

  • rubygems-3.2.12.tgz
    b069177ca78878fbcd08e74b3ebd38b1e1b8b164f1d22b4726a60a5299830344
  • rubygems-3.2.12.zip
    c2abef085cf275403c1466b3f316d49b6e85d30ab1d6f4c24c32feeb70c8d774
  • rubygems-update-3.2.12.gem
    92f34de00b5cf4ece5c3ea52c59abd8e80c563ab409cf9e8c42c0ad1b050d4da
GoRails Screencasts 

Sharing Cookies with Subdomains in Rails

Want to login your user across all subdomains in your Rails app? Here's how.
Saeloun Blog 

Rails 6.1 adds config option to control image_tag loading attribute

Page load times are proportional to the amount of data that needs to be rendered on the screen. So reducing the page size will reduce page load time as well.

According to HTTPArchive, images are the most requested asset type for most websites and usually take up more bandwidth than any other resource. So it goes without saying that one of the first elements to be sacrificed for better load times are the use of images!

But it isn’t always optimal to do that.

With lazy loading of images, the initial load of the page does not request images. Only as the relevant portion of the screen comes into view, the respective images are loaded. This usually involved complex JavaScript packages to be…

Honeybadger Developer Blog 

How Elixir Lays Out Your Data in Memory

Higher-level languages hide the details to boost developer experience and productivity. However, this leads to a loss of understanding of the underlying system, preventing us from squeezing the highest level of efficiency and performance from our programs. Memory management is one of the aspects abstracted away from us in this trade-off. In this series, we'll take a look at how the BEAM VM works in this regard and learn to make better decisions when writing Elixir code.

What is memory management

Programs operate on top of values or a collection of values. These values are stored in memory so that they may be referred back to whenever needed to perform a particular operation. Understanding…

Everyday Rails 

Persist existing data when setting up a Rails development environment

Rails support for automating development environment setup includes a behavior that may surprise you! Here's how I addressed it in my applications.
OmbuLabs Blog 

Introducing Hotwire

One of the most visible and controversial new developments with the release of Rails 6.0 is Hotwire. Like anything in web development, the growing popularity of single page applications using JS frameworks has sparked some resistance. Arguably, the duplication of logic that single page applications often require violates the DRY principle. There are also many developers who would like the responsiveness of single page applications without all of the client side JavaScript and it's associated headaches. There are a considerable number of developers who'd like the pendulum to swing back towards the server, but maybe keep some of the more desirable aspects of the SPA pattern. Hotwire is a…

John Nunemaker 

FounderQuest: Talking Startups and Pricing Strategies

I got to use my new Yeti mic for an interview on FounderQuest, a podcast by the fine folks who run Honeybadger. We had a blast talking about business models, pricing, cardinality, config, a/b testing, scientist and more. Give it a listen!

The RubyMine Blog : The Ruby on Rails IDE | JetBrains Blog 

RubyMine 2021.1 EAP5: Improvements for Usability, working with HTML, CSS, JS, and more

RubyMine 2021.1 EAP5 is now available! In this post, you’ll learn about improvements for usability, working with HTML, CSS, and JavaScript files, and VCS support.

Here are the main highlights:

DOWNLOAD RUBYMINE 2021.1 EAP

Important! RubyMine EAP builds are not fully tested and might be unstable.

HTML files preview

We’ve added a new built-in browser preview to RubyMine. It allows you to quickly preview any changes you make to your HTML, CSS, and JavaScript files. Any changes you make in the IDE will be immediately saved and the preview will update on the fly.

To open the preview, click on the…

Boring Rails: Skip the bullshit and ship fast |  

Pluck single values out of ActiveRecord models or Enumerables

Rails has a great, expressive term called pluck that allows you to grab a subset of data from a record. You can use this on ActiveRecord models to return one (or a few) columns.

But you can also use the same method on regular old Enumerables to pull out all values that respond to a given key.

Usage

In Rails, use pluck to query a subset of columns.

Shoe.all.map(&:name)
# SELECT "shoes.*" from "shoes"
# => ["Air Force 1", "NMD_2", "Air Jordans", ... ]
# This returns an array with all shoe names, but our database query pulled down all of the columns on the `shoes` table

Shoe.pluck(:name)
# SELECT "shoes.name" from "shoes"
# => ["Air Force 1", "NMD_2", "Air Jordans", ... ]
# Same result,…

You can also…

Remote Ruby 

Launching 12in12.io, Dependency Confusion Attack, and Conventional Commits

[00:02:42] Andrew does a follow up from last week when he talked about moving and archiving repos and he gives an update. Jason tells us problems they’ve had with Dependabot.
[00:05:36] We learn about Andrew perfecting a gem release workflow and using Conventional Commits.
[00:09:43] Chris was busy this week and he tells us about a live stream he did with Freek Van der Herten, who created an app called Ray. [00:13:15] Find out about the product streaming Chris did with 12in12.io and how he did a zoom call to talk about job boards and domaining with Jon Hainstock and Peter Askew. Peter is famous for the VidaliaOnions.com domain he bought, which is an interesting story you really need…
Saeloun Blog 

Rails allows benchmark method to be called from anywhere

Latest changes in Rails allows benchmark method to be called from anywhere.

Before

Before this change, we could use it in views or controllers.

<% benchmark '=== Processing invoices ===' do %>
  <%= process_invoices %>
<% end %>

But, if we have to benchmark some methods in models or services we needed to do something like this:

require 'benchmark'

def process
  logger.info("=== Processing invoices ===")
  logger.info Benchmark.measure { process_invoices }
  # or
  logger.info Benchmark.realtime { process_invoices }
end

This would log the details in the following way.

=== Processing invoices ===
0.406537   0.082624   0.489161 (  0.503110)
0.5047359999734908

We could also use the…

Saeloun Blog 

Rails introduces new syntax for enum

Latest changes in Rails introduces new syntax for defining an enum.

Before

The previous syntax includes the key value pair for the enum name, its enum values, and the options.

class Post < ActiveRecord::Base
  enum status: [ :draft, :published, :archived ], _prefix: true, _scopes: false
  enum category: [ :free, :premium ], _suffix: true, _default: :free
end

After

The new syntax has made the enum name and the values a separate argument and the enum options can be passed as key value pairs.

class Post < ActiveRecord::Base
  enum :status, [ :draft, :published, :archived ], prefix: true, scopes: false
  enum :category, [ :free, :premium ], suffix: true, default: :free
end

These changes…

Awesome Ruby Newsletter 

💎 Issue 249 - Ruby on Rails is the world’s fastest web framework for startups

John Nunemaker 

Flipper.enable(☁️)

I previously wrote about why I was working on Flipper Cloud. Since then, everything has changed.

We bought Speaker Deck back from GitHub. My wife and I had another child. Microsoft acquired GitHub. I left GitHub. I joined Box Out Sports. Steve and I  launched Speaker Deck Pro. It has been a busy two years!

And I'd be remiss not to mention the biggest change of all – the pandemic.

All of these things led to Flipper Cloud getting pushed to the side. I mean, it was running and working great.

We used it on both Box Out and Speaker Deck. But no one else could. Well, save the lucky few who guessed the magic word. Haha!

Following the release of Speaker Deck Pro, Steve and I knew it was Flipper's turn.…

Ruby Weekly 

Ruby became Ruby 28 years ago

#541 — February 25, 2021

Read on the Web

💡 We've had some great feedback about the Tip of the Week so we want to keep it going, and it's back this week without another method that may have passed you by :-) Our feature this week is also essentially a giant pile of tips for using irb.
__
Peter Cooper, editor

Ruby Weekly

The Hidden Gems of Ruby's irb — Lots of good info here, including how IRB handles sessions, how to enable tracing, the new measure command, and how to customize your IRB. Oh, and there’s an easter egg, too…

Valentino Stoll

Opal 1.1: A Ruby to JavaScript Compiler — An…

JRuby.org News 

JRuby 9.2.15.0 Released

The JRuby community is pleased to announce the release of JRuby 9.2.15.0

JRuby 9.2.x is compatible with Ruby 2.5.x and stays in sync with C Ruby. As always there is a mix of miscellaneous fixes so be sure to read the issue list below. All users are encouraged to upgrade.

As we are still actively working on 9.3.0.0 we decided to put out another 9.2.x release to fix some of the more recently reported issues.

Compatibility

  • Several issues were fixed in process management, to avoid raising unexpected errors, properly launch executables on Windows, and preserve quoting when also doing a chdir. (#6466, #6477, #…
Scott Bartell 

Finding and Fixing Missing Indexes in a Rails app

When looking at the “Most time consuming” database operations for our application in New Relic and I came across something that looked odd to me.

Looking at the list I noticed two operations that I wouldn’t have expected to be among the most time consuming: OrderCreditTransaction find and Discount find.

In this post we’re going to dig into OrderCreditTransaction find find the problem and fix it.

Screenshot from New Relic showing the most time consuming database operations over the last 7 days with the Postgres `OrderCreditTransaction find` operation at the top.

What does “Most time consuming” mean?

“Most time consuming” tells you how much total time was spent doing an operation in a minute. This is equivalent to the average throughput (number of calls/minute) multiplied by the average response time.

For example if User find has an average response…

Julia Evans 

A little tool to make DNS queries

Hello! I made a small tool to make DNS queries over the last couple of days, and you can try it at https://dns-lookup.jvns.ca/.

I started thinking about this because I’m working on writing a zine about owning a domain name, and I wanted to encourage people to make a bunch of DNS queries to understand what the responses look like.

So I tried to find other tools are available to make DNS queries.

dig is kind of complicated

I usually make DNS queries using dig, like this.

$ dig jvns.ca

; <<>> DiG 9.16.1-Ubuntu <<>> a jvns.ca
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 8447
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL:…
Boring Rails: Skip the bullshit and ship fast |  

Never mix up greater/less than when comparing dates again

When it comes to compare dates, for some reason my brain really struggles. I mix up < and >= all the time and end up flipping them.

Is start_date greater than end_date? Or vice-versa? I get confused because I think about dates in terms of before and after not greater_than or less_than.

Usage

Luckily, Rails is here to save the day and make sure I never make this mistake again by adding before? and after? for all Date-related comparisons.

start_date = Date.new(2019, 3, 31)
end_date = Date.new(2019, 4, 1)

start_date.before? end_date
#=> true
end_date.after? start_date
#=> true

start_date = Date.new(2020, 8, 11)
end_date = Date.new(2018, 8, 11)

start_date.before? end_date
#=> false

I…

Ruby Magic by AppSignal 

Troubleshooting ActiveRecord Performance

ActiveRecord is Ruby on Rails’ most magical feature. We don’t usually need to worry about its inner workings, but when we do, here’s how AppSignal can help us know what’s going on under the hood.

What Is ActiveRecord?

To talk about ActiveRecord, we need to first think of frameworks, specifically about MVC frameworks. MVC stands for Model-View-Controller, and it’s a popular software design pattern for graphical and web applications.

MVC frameworks are composed of:

  • Model: handles business logic and data persistence.
  • View: drives the presentation layer and draws the user interface.
  • Controller: ties everything together.

ActiveRecord is the model component in the Ruby in Rails…

Ruby on Rails Podcast 

359: Sales for Software Developers with Evie Zawada

We’re continuing our Developer Life Series. Brittany tapped her good friend, Evie Zawada, to guest on the podcast to discuss sales tactics, identifying personas and how important it is to listen. She offers advice for developers who might find themselves selling a product or themselves for a job.

Links for this episode:

Brought to you by:

Scout APM

Give Scout a try today with a free 14-day trial, and experience firsthand why Rails developers worldwide call Scout their best friend. And as an added bonus for Ruby on Rails listeners: Scout will donate $5 to the open source…

Greater Than Code 

223: Emotions, Achievement, Joy, and Goals with David MacIver

02:15 - David’s Superpower: Being Confused

11:56 - Daily Writing

15:47 - Learning to Be Better at Emotions

23:22 - Achievement and Joy as Aspirational Goals

Reflections:

Jessica: Trying not knowing yourself.

Rein: You shouldn’t be the owner of all your desires. Instead, you should measure your life by how well you follow the intentions that arise out of your values.

Jacob: Thinking of yourself as the sum of all of the habits you maintain or…

Da…

All Ruby Podcasts by Devchat.tv 

RUBY 487: Our Development Setups

Dave, Luke, and Chuck dive into their development setups. They talk through the different Operating Systems, IDEs, text editors, command lines, desks, chairs, etc. we all use to build our Ruby and Rails applications.

Panel

  • Charles Max Wood
  • Dave Kimura
  • Luke Stutters

Sponsors

Links

Picks

Rails with Jason 

084 - Debugging Techniques with Noah Gibbs

In this episode I talk with Noah Gibbs, author of Rebuilding Rails, about debugging techniques, the scientific method, a useful concept called "the presenting complaint", and more.

Links:

Long live Ruby 

Rails design patterns

This article is a high-level overview of design patterns that are commonly used in Ruby on Rails applications. I will also mention the advantages and disadvantages of using design patterns as, in some cases, we can harm the architecture instead of making it better.
BigBinary Blog 

Rails 7 adds Enumerable#maximum

Rails 7 adds support for Enumerable#maximum and Enumerable#minimum to easilycalculate the maximum and minimum value from a collection of enumerableelements.

Before Rails 7, we could only achieve the same results with a combination ofmap & max or min functions over the enumerable collection.

=> Item = Struct.new(:price)=> items = [Item.new(12), Item.new(8), Item.new(24)]=> items.map { |x| x.price }.max=> 24=> items.map { |x| x.price }.min=> 8

This is simplified with Rails 7's newly-introduced maximum and minimummethods.

=> items.maximum(:price)=> 24=> items.minimum(:price)=> 8

These methods are available through Action Controller'sfresh_whenandstale?for convenience.

# Before Rails 7def index …
The Bike Shed 

282: What is Normal?

On this week's episode, Chris adds Dead Man's Snitch to a personal project and considers "what is the app doing at runtime?" as he touches on the importance of creating observable systems. Steph shares analyzing a site's traffic and using Apache Bench for simple load testing. They also respond to a listener question about creating environment-specific data for data-intensive applications.


This episode is brought to you by SPOTcon. Tune in to Scout APM's first conference, and join for developers from around the world to meet, engage with, and learn about solutions that drive leading-edge transformation in application development by registering for free today!


Boring Rails: Skip the bullshit and ship fast |  

Super readable String operations with `delete_prefix` and `delete_suffix`

One reason I love writing Ruby is that it’s optimized for programmer happiness. The Ruby community values code that is super readable.

Programmers coming from other ecosystems are often shocked at much Ruby looks like pseudo-code. Between the standard library and extensions like ActiveSupport, working with Ruby means you can write code in a natural way.

A great example of this are the String methods delete_prefix and delete_suffix.

Usage

You can use delete_prefix to, as the name says, delete a substring from the beginning of a string.

"BoringRails!".delete_prefix("Boring")
#=> "Rails!"

"#programming".delete_prefix("#")
#=> "programming"

"ISBN: 9780091929787".delete_prefix("ISBN: ")
#…
Rebased Blog 

Redis rate limiter

At Rebased we have an internal time tracking project called Harmonogram. Its backend is built in Ruby on Rails. It started as a playground for new hires to get used to company culture and conventions, but over time grew into a fully-functional tool. When I joined, the application was already...
Rails Performance Audit and Tuning Consultant for Hire 

How to Avoid the Most Dangerous Word in Software Development

J-U-S-T. Those four characters can be significantly detrimental to a software development process. In this blog post, I’ll describe how the “just keyword” can affect team’s communication and how to avoid misusing it on Slack.

Let’s “just” do it

You’ve probably been there. Your product manager shares his brand new plan on the Slack channel:

“Why don’t we just add this cool new feature to our application?”

or your colleague got the wrong idea about scaling after reading a HackerNews story:

“Let’s just migrate our infrastructure to Kubernetes…“

“Just” is toxic and dangerous. It implicitly suggests that the proposed task is straightforward. It undermines the discussion about the issues…

Andy Croll 

Use Rails URL helpers outside views and controllers

Occasionally you’ll need to generate a URL to your own application, outside of views or controllers. In these places, URL helpers are available. These helper methods are generated from your routes, e.g. user_books_path(user).

Instead of …

…hard coding a URL:

class RequestUserCallBackJob < ApplicationJob
  def perform(user)
    Net::HTTP.post(
      "http://userinfoapi.com/",
      body: {callback_to: "https://myapp.com/user/#{user.id}"})
  end
end

Use…

…the route helpers that Rails includes automatically in controllers.

class RequestUserCallBackJob < ApplicationJob
  include Rails.application.routes.url_helpers

  def perform(user)
    Net::HTTP.post(
      "http://userinfoapi.com/",

URL helpers are used in the context of a web request, i.e. within a…

Everyday Rails 

Docker containers for Rails development environments, part 2: Setup

In our first experiment, let's see what it takes to get a Rails app to boot in a Visual Studio Code devcontainer.
Boring Rails: Skip the bullshit and ship fast |  

Setting CSS classes in Markdown with Jekyll / Bridgetown

Writing blog posts in Markdown is just great. This blog is written in Markdown!

But sometimes you might be tempted to drop down to raw HTML to add some extra styling.

For example maybe you want to write this content in markdown but have it apply a “pro-tip” CSS class so that it looks like…well, this!

Usage

Popular Ruby static site generators like Jekyll and Bridgetown use Kramdown under-the-hood to render your Markdown by default.

In Kramdown, there is a feature called “Block Inline Attribute Lists”, which is an extension of standard Markdown syntax.

A simple paragraph with an ID attribute.
{: #para-one}

> A blockquote with a title
{: .pull-quote }

You use {: CSS_SELECTOR } to…

Remote Ruby 

Jason's run in with the cops, Andrew deletes his GitHub, and Madmin launches?

[00:00:22] The guys share stories of things that happened to them this past week.
[00:06:30] Jason announces he got all his testing videos done for his course and it pushed him to do more work on the StimulusReflex testing library. 
[00:09:25] Chris asks the guys if they knew of a library that has test helpers for both frameworks.  [00:12:22] Jason tells us his testimonials are done and he’s hit a weird spot with the app being a little bit incomplete, and he’s thinking about making a video.
[00:14:20] Jason talks about when he’ll launch the video since he just has two left. Chris announced the OmniAuth 2.0 course is out and what happened. [00:17:08] Jason and Chris talk about issues…
Josh Software 

Flutter – Best practices to start with

Flutter SDK is Google’s UI toolkit for crafting beautiful, natively compiled applications for mobile, web, and desktop from a single codebase. It uses dart language to build apps. So I assume you have already gone through the basics of Dart language. So let’s start on this one by one. 1. Follow clean architecture while creating your … Continue reading Flutter – Best practices to start with
Awesome Ruby Newsletter 

💎 Issue 248 - Game Development using DragonRuby Game Toolkit by Amir Rajan

Hi, we're Arkency 

Discord-to-Slack bot hosted on repl.it

Discord-to-Slack bot hosted on repl.it

The story

So we started using Discord alongside Slack recently. The selling point were voice channels and screen streaming. It made voice conversations much smoother and more async friendly and made us overall closer to each other. More context here.

Basically, whenever someone joins a voice channel it means:

  • I’m available to talk, or
  • I don’t mind company.

But since we’re using Slack as the primary means of communication, not everyone in our team is used to having Discord open at all times. We need one thing: an integration that would notify us on Slack, whenever someone joins a voice channel on Discord:

Let’s do it

We’ll need to:

  • Set up a…
Giant Robots Smashing Into Other Giant Robots 

Simplifying Tests by Extracting Side-Effects

Functional programming gives us a mental model that can be helpful when looking at unit testing our object-oriented code. In particular, it gives us two terms:

  1. Pure functions - these are deterministic methods with explicit inputs and outputs (e.g. no implicit dependency on the system clock). This kind of method is the easiest to test.
  2. Side-effects - Any source of inputs or outputs for a method that are not part of the arguments or return value. Examples include calls to Time.now, or writing the output to a file. These types of methods are non-deterministic, which makes them trickier to test and usually involves some mocking or stubbing.

Test-driven development, object-oriented design,…

Ruby Weekly 

Bundler tightens its security

#540 — February 18, 2021

Read on the Web

💡 The Tip of the Week is back – see the end of the issue for that. It covers a Ruby 2.7 feature that makes a reasonably common task a single call and I'm very glad for its addition to the language 😄
__
Peter Cooper, editor

Ruby Weekly

A More Secure Bundler: How We Fixed Our Source Priorities — Last week there was a major story where a non-malicious developer pushed libraries to public repositories with the same name as private packages and these then took precedence over the private packages several companies’ systems expected to install. Uh-oh! While

Boring Rails: Skip the bullshit and ship fast |  

Use Heroku Dataclips to share query and do ad-hoc data exports

Heroku Dataclips enable you to create SQL queries for your Heroku Postgres databases and share the results with colleagues, third-party tools, and the public. Recipients of a dataclip can view the data in their browser and also download it in JSON and CSV formats.

Heroku Dataclips

Usage

If you are hosting your app on Heroku, you might need to run some ad-hoc queries or share a report. Instead of generating an admin page or a CSV report, you can make a Dataclip that attaches to your production database and run raw SQL queries.

The editor has autocomplete features for tables and columns and you can export the data to CSV or JSON.

Super handy for one-off SQL queries or barebones reporting and way better…

SciRuby 

Tensors using NumRuby

Tensor word can have slightly different meaning depending upon the nature of study, like it’s defined differently in Physics, slightly different in computer science. In computer terms, it is basically a n-dimensional array. A scalar (one value) is a tensor with 0 dimensions, a vector is a tensor with 1 dimension, a matrix is a tensor with 2 dimensions.

It’s possible to define a tensor in Ruby using the Array class of Ruby but it gets tedious when defining multi-dimensional tensors. Also, the Array object is designed to be heterogeneous which means that the elements of the array can be of different type or different classes which would seem as a plus point overall but it has a huge…

The RubyMine Blog : The Ruby on Rails IDE | JetBrains Blog 

RubyMine 2021.1 EAP4 is available!

In this post, you’ll learn about RubyMine’s new features for working with style sheets, URLs, and the JSON lines format, as well as several usability improvements.

Here are the main highlights. Please try them out and share your feedback with us.

DOWNLOAD RUBYMINE 2021.1 EAP

Important! RubyMine EAP builds are not fully tested and might be unstable.

Selector specificity for style sheets

In style sheets, you can now check the specificity of your selectors. Just hover over a selector, or focus on it and press F1 (Ctrl+Q), to invoke the Documentation popup with the information.

All Ruby Podcasts by Devchat.tv 

RUBY 131: How to Learn

This is a repeat episode of Ruby Rogues. Here's the original link https://devchat.tv/ruby-rogues/131-rr-how-to-learn/

Sponsors

Riding Rails 

Rails 6.1.3 has been released

Hi everyone,

I am happy to announce that Rails 6.1.3 has been released.

CHANGES since 6.1.2

To view the changes for each gem, please read the changelogs on GitHub:

To see a summary of changes, please read the release on GitHub:

6.1.3 CHANGELOG

Full listing

To see the full list of changes, check out all the commits on GitHub.

SHA-256

If you’d like to verify that your gem is the same as…

Ruby Together News 

January 2021 Monthly Update

Hello! Welcome to the monthly update. During January, our work was supported by Zendesk, DigitalOcean, Stitch Fix, and many others.

ruby together news

In January, Ruby Together was supported by 40 different companies, including Ruby member Zendesk and Sapphire member Stripe. 6 companies joined as new members.

On top of those companies, 6 new developers signed up as members, including Abdullah Esmail, Marco Roth, Shaun McCormick, and Chance Feick. In total, we were supported by 106 developer members. Thanks to all of our members for making everything that we do possible. <3

rubygems & bundler news

In January, we released new versions of Bundler v2.2.5, v2.2.6, v2.2.7, and v2.2.8, and…

Rebased Blog 

Complex columns in PostgreSQL with Rails

TBD
Martian Chronicles, Evil Martians’ team blog 

Serverless TypeScript: A complete setup for AWS SAM Lambdas

Authors: Andrey Novikov, Backend Developer at Evil Martians and Sergey Alexandrovich, Lead Backend Developer at Evil Martians

Learn to write Lambdas for AWS Serverless Application Model (SAM) in pure TypeScript without the need to compromise your development workflow. See how to rely on SAM’s shared layers to package your dependencies. Refer to our template GitHub repository so you can build and deploy example TypeScript Lambdas alongside the complete production environment.

Serverless functions (or Lambdas in AWS-speak) are a great choice when your application load tends to be highly irregular, and you want to avoid provisioning virtual servers and setting up the full environment to…

Code with Jason 

Don’t wrap instance variables in attr_reader unless necessary

I’ve occasionally come across advice to wrap instance variables in attr_reader. There are two supposed benefits of this practice, which I’ll describe shortly. First I’ll provide a piece of example code.

Example of wrapping instance variables in attr_reader

Original version

Here’s a tiny class that has just one instance variable, @name. You can see that @name is used in the loud_name method.

class User
  def initialize(name)
    @name = name
  end

  def loud_name
    "#{@name.upcase}!!!"
  end
end

attr_reader version

Here’s that same class with an attr_reader added. Notice how loud_name now references name rather than @name.

class User
  attr_reader :name

  def initialize(name)
    @name =…
Boring Rails: Skip the bullshit and ship fast |  

Ensure required environment variables are set when booting up Rails

It’s common to use environment variables to configure external services or other options in a Rails app. These ENV_VARS usually are not checked into source control, but rather configured per environment.

Rails has the concept of initializers, which is code run during the boot phase of a Rails app.

You can add a custom initializer to check that required environment variables are set to avoid exceptions later on when your code expects a value to exist.

Usage

Create a new initializer in your app and add the required variables:

# config/initializers/01_ensure_environment.rb

if Rails.env.development?
  %w[
    AWS_ACCESS_KEY_ID
    AWS_SECRET_ACCESS_KEY
    S3_BUCKET
    ALGOLIA_ID
   …
Ruby on Rails Podcast 

358: CSS is a Cat with Utah Newman

Utah Newman is a self taught Front end engineer with a passion for accessibility at Brightwheel. She and Brittany discuss the origin story behind her cat, border-radius: 50%, how important help is and how to navigate ADHD as a developer.

Links for this episode:

Brought to you by:

Scout APM

Give Scout a try today with a free 14-day trial, and experience firsthand why Rails developers worldwide call Scout their best friend. And as an added bonus for Ruby on Rails listeners: Scout will donate $5 to the open source project of your choice…

Ruby Magic by AppSignal 

Using Webpacker in Your Ruby on Rails Application — a Deep Dive

At the beginning of the internet age, websites were much simpler and not very interactive. With the advancement of technology, devices, and programming languages, they became more complex and consisted of several files, including assets like images and CSS stylesheets.

The more interactive your website is, the more JavaScript code you have to use. To use such code, you have to include all HTML code files using the script tag. Such an approach is error-prone because you have to remember to include every single file and keep the correct order, otherwise, your code may not work. With the Webpack tool, these problems go away. Webpacker is a bridge between Webpack and a Rails application.

This…

Greater Than Code 

222: Evaluating Human Performance with Elyse Robinson

02:05 - Elyse’s Superpower: Fearlessness

  • Moving to Mexico
  • Living in Mexico
  • Dual-Existing and Codeswitching
  • Elyse’s Podcast & Blog
  • A Day In The Life

19:41 - Auditor => IT Consultant

24:02 - Broken Interview Processes and Evaluating Human Performance

Reflections:

Damien: The ways that I can be fearless.

Arty: You only have one life. Don’t put limits on it.

Rein: Being intentional about making our networks more inclusive.

Elyse: There isn’t a pipeline problem in IT.

This episode was brought to you by @therubyrep of DevReps, LLC. To pledge your support and to join our awesome Slack community, visit patreon.com/greaterthancode

RubyGems Blog 

3.2.11 Released

RubyGems 3.2.11 includes enhancements.

To update to the latest RubyGems you can run:

gem update --system

To install RubyGems by hand see the Download RubyGems page.

## Enhancements:

  • Optionally fallback to IPv4 when IPv6 is unreachable. Pull request #2662 by sonalkr132

SHA256 Checksums:

  • rubygems-3.2.11.tgz
    fee5620d279d51c85816b8c7a5a27a1e704bacabaedffb25b31b6c161d071053
  • rubygems-3.2.11.zip
    ba3f8432a1a99f51424a15a819eae04cd25750c754680183c09c4231404282a8
  • rubygems-update-3.2.11.gem
    9bdcf17a4da02deab2a604fdc5148af9438012b5823980c29ac3f51e17eba58f
Hi, we're Arkency 

3 tips to tune your VCR in tests

3 tips to tune your VCR in tests

In this post I describe 3 things that have grown my trust in VCR. These are:

  • decompressing stored responses
  • not allowing unused mocks
  • disabling VCR where not explicitly needed

Read on to see why I’ve specifically picked them.

What is VCR from a bird’s eye view

VCR is a tool which I’d classify as useful in snapshot testing. You record a snapshot of an interaction with a System Under Test. Once recorded, these interactions are replayed from stored files �— snapshots.

VCR specifically records HTTP interactions and stores results of such in YAML files called “tapes”. A tape consists of series of requested URL, request headers, response headers and returned…

Honeybadger Developer Blog 

Code Loaders in Ruby: Understanding Zeitwerk

Code Loaders in Ruby - Understanding Zeitwerk

With Zeitwerk, you can streamline your programming knowing that classes and modules are available everywhere.

What are Code Loaders?

Code loaders let developers define classes and modules across different files and folders and use them throughout the codebase without explicitly requiring them. Rails is a good example of a piece of software that uses code loaders. Programming in Rails doesn't require explicit require calls to load models before using them in controllers. In fact, in Rails 6, everything in the app directory is auto-loaded on app boot, with a few exceptions.

While it is easy to think code loading is all about making calls to re…

Scott Bartell 

RSpec Rails Tip: `have_http_status` matcher

Sometimes you need to test the status code of a response in a controller, request, or feature spec. With the rspec-rails gem this can be done cleanly using the have_http_status matcher.

have_http_status can take three different arguments:

  1. numeric code (200, 404, etc)
  2. status name as defined in Rack::Utils::SYMBOL_TO_STATUS_CODE (:ok, :not_found, etc)
  3. generic status type (:success, :missing, :redirect, or :error)

This means that these are actually different:

it { is_expected.to have_http_status(:ok) }
it { is_expected.to have_http_status(:success) }

Because :ok, as defined in Rack::Utils::SYMBOL_TO_STATUS_CODE, only matches status 200 while :success is a generic status type that…

Accordin…

Boring Rails: Skip the bullshit and ship fast |  

Search and debug gems with `bundle open`

Ever get frustrated trying to search through code on GitHub? Or wish you could put a breakpoint in a gem so you could figure out what it was doing?

Don’t mess around with cloning the gem repo or monkey patching code in your own app. Use bundle open instead.

Example of bundle open command

Usage

In your shell, run the command: bundle open GEM_NAME

bundler will open the source code for the exact version of the gem you’ve got installed in your editor. You can search the code inside your editor and even add breakpoints or make code changes locally to test out things.

Options

The bundle open command launches the editor that you’ve set via the EDITOR or BUNDLER_EDITOR environment variables. You can set this to be vim, e…

Rails with Jason 

083 - How to Estimate Accurately with Matt Swanson

If you've ever experienced the pain of having woefully underestimated something, this episode is for you. In this one I talk with Matt Swanson about how to estimate accurately as well as why I'm not a big fan of story points.

Links:

Long live Ruby 

The family of anonymous functions

Anonymous functions are an integral part of Ruby’s identity and provide flexibility for any kind and size of the codebase. This article is a deep dive into blocks, procs, and lambdas that will help you to understand how these functions differ from each other and how you can benefit from using them.
The Bike Shed 

281: Finding That Middle Ground

On this week's episode, Steph and Chris tackle a listener question around switching from mostly-developing, to mostly-communicating and the tactics they've used to balance these facets of their work. They also discuss the new error objects in Rails 6.1, the value of breakable toys, and the importance of keeping presentational concerns out of the data model.


This episode is brought to you by ScoutAPM. Give Scout a try for free today and Scout will donate $5 to the open source project of your choice when you deploy


Become a Sponsor of The Bike Shed!

Sponsored By:

Honeybadger Developer Blog 

ActiveRecord For Databases Without Unique Ids

Sometimes unique situations and things out of our control lead to wildly unorthodox requirements. Recently, I had an experience where I needed to use ActiveRecord without relying on the database ID for any records. If anyone is considering doing the same, I highly recommend finding another way! But, let's move on to the rest of the story.

Decisions were made. Smaller databases (clones in structure but not in data) needed to be merged. I joined the project just as the team was putting the finishing touches on a script that copies and pastes database records from one database to another. It copied everything exactly as-is, including IDs.

Database A

id fruit user_id ... ... ... 123 o…
Saeloun Blog 

Rails 6.1 adds query method associated to check for the association presence

Rails 6.1 adds query method associated similar to ActiveRecord::Relation#missing. missing checks for the orphan objects, while associated checks for the association presence.

Example

Let us consider the following models.

# app/models/manager.rb
class Manager < ApplicationRecord
  has_many :job_listings
end
# app/models/job_listing.rb
class JobListing < ApplicationRecord
  has_many :job_applications
  belongs_to :manager
end
# app/models/job_application.rb
class JobApplication < ApplicationRecord
  belongs_to :job_listing
end

Before Rails 6.1

Now let us try to find all the job listings which have a manager assigned.

[1] pry(main)> JobListing.joins(:manager).where.not(managers: {id: n…
RubyGems Blog 

3.2.10 Released

Installing rubygems 3.2.10 also installs bundler 2.2.10 as a default gem, which includes a fix to a security problem regarding source priority. Have a look at bundler’s blog post for more information.

RubyGems 3.2.10 also includes documentation improvements.

To update to the latest RubyGems you can run:

gem update --system

To install RubyGems by hand see the Download RubyGems page.

## Documentation:

  • Add a gem push example to gem help. Pull request #4373 by deivid-rodriguez
  • Improve documentation for required_ruby_version. Pull request #4343 by AlexWayfer

SHA256 Checksums:

  • rubygems-3.2.10.tgz
    5528906719677368942df92aea38581d598ccf31c4bd3261ebf9c6cf309bd967
  • rubygems-3.2.10.…
Bundler Blog 

A more secure bundler: We fixed our source priorities.

NOTE: The part about the Bundler release in this blog post is not currently relevant. We had to revert the change since it created breaking behavior for our users. We’ll remove this note once we release a properly working version that implements this improvement.

What happened?

Last week an article about “Dependency Confusion” hit the news, where a developer was able to make thousands of dollars on bug bounty programs from big tech companies, by pushing libraries to public repositories that ended up unintentionally being installed into these companies servers.

The developer was able to expose (in a non-malicious way) a vulnerability present in well-known dependency managers, where…

Ruby Yagi 🐐 

How to call methods dynamically using string of method name

I was working on a feature for my Rails app, which allows merchant to set fulfillment times on each day like this :

fulfillment_time

The main feature is that once an order is placed, the customer can’t cancel the placed order after the fulfillment time starts on that day (or on tomorrow).

The fulfillment start times are saved in different columns like this :

create_table "fulfillments", force: :cascade do |t|
  t.time "monday_start_time", default: "2000-01-01 00:00:00", null: false
  t.time "tuesday_start_time", default: "2000-01-01 00:00:00", null: false
  t.time "wednesday_start_time", default: "2000-01-01 00:00:00", null: false
  t.time "thursday_start_time", default: "2000-01-01 00:00:00", null: fa…

To check if the fulfillment time has started, my app will get the current day of week…

Boring Rails: Skip the bullshit and ship fast |  

Automatically cast params with the Rails Attributes API

A common practice in Rails apps is to extract logic into plain-old Ruby objects (POROs). But often you are passing data to these objects directly from controller params and the data comes in as strings.

class SalesReport
  attr_accessor :start_date, :end_date, :min_items

  def initialize(params = {})
    @start_date = params[:start_date]
    @end_date = params[:end_date]
    @min_items = params[:min_items]
  end

  def run!
    # Do some cool stuff
  end
end

report = SalesReport.new(start_date: "2020-01-01", end_date: "2020-03-01", min_items: "10")

# But the data is just stored as strings :(
report.start_date
# => "2020-01-01"
report.min_items
# => "10"

You probably want start_date to…

EquiValent 

Rails ActiveStorage AWS S3 bucket policy permissions

Steps:

create a AWS s3 bucket and then create a new AWS IAM user:

  1. create new user in AWS IAM (copy access_key and sectet and store them to Rails credentials)
  2. on “Set Permission” step click on “Attach existing policies directly”
  3. click on “create policy” button
  4. new window will popup where you paste the JSON policy from section “AWS Policy” bellow. Name it what you want
  5. on “Set Permission” select the newly created policy (you many need to reload the page so it appears)

Best practices for AWS are that for every Rails app enviroment you should have own user and own bucket. That means for production create s3 bucket my-project-prod and IAM user my-project-prod and for staging s3…

Running with Ruby 

RubyGems dependency confusion attack side of things

Note: This article is not to deprecate any of the findings and achievements of Alex Birsan. He did great work exploiting specific vulnerabilities and patterns. It is to present the RubyGems side of the story and to reassure you. We actively work to provide a healthy and safe ecosystem for our users.

After reading the Dependency Confusion: How I Hacked Into Apple, Microsoft and Dozens of Other Companies I felt, that the Ruby community requires a bit of explanation from people involved in RubyGems security assessment. So here it is.

It’s you who is responsible for the security of your software, and bugs do exist

First of all, let me remind you that your system security should never rely…

Everyday Rails 

Docker containers for Rails development environments, part 1: Introduction

Let's experiment with building sensible devcontainers for Rails. Here's the plan.
Emmanuel Hayford 

Getting Started With tmux: Just The Basics To Get Up And Running.

tmux is a terminal multiplexer for Unix-like operations systems. I’ve gone years without it with lots of regrets.

I have my projects and work with a team to build products. When I’m not working on a team project, I’m fidgeting with my side hustle. The number of times I’ve started various projects and have had to navigate between the same folders is innumerable.

Perhaps you’re reading this because you want to save yourself from moving back and forth between windows and save time along the way. Let me show you how to get started.

With tmux, you’ll be fine if you know how to use sessions, windows and panes. You create windows inside sessions, and each window can have pane. A pane is a…

On the Edge of Ruby 

Correct Delegation with Ruby 2.6, 2.7 and 3.0

While looking at how a few gems handle delegation on Ruby 2.7, I noticed that many of them are unfortunately incorrect. The official blog post about keyword arguments changes in Ruby 2.7 and Ruby 3.0 is rather long and might be unclear. So I will keep this one really short and to the point.

I am a CRuby committer which discussed and designed the keyword arguments changes along with Jeremy Evans and Yusuke Endoh.

The Only Correct Way

There is actually just a single way to do delegation that works in Ruby <= 2.6, in Ruby 2.7 and in Ruby >= 3:

def foo(*args, &block)
  target(*args, &block)
end
ruby2_keywords :foo if respond_to?(:ruby2_keywords, true)

It’s simple: ruby2_keywords is the…

Boring Rails: Skip the bullshit and ship fast |  

Show relevant chunks of text with Rails `excerpt` helper

The Rails helper excerpt can extract a chunk of text that matches a certain phrase, no matter where in the string it is.

Imagine you wanted to display a list of emails matching a certain search term:

Simply filter down your records and then use excerpt on the email body.

Usage

Here’s what your view might look like to build this feature.

<%= link_to email do %>
  <div class="flex justify-between items-center">
    <p class="text-sm font-medium text-gray-900">
      <%= email.sender_name %>
    </p>
    <%= local_time_ago email.received_at %>
  </div>
  <p class="text-sm text-gray-700">
    <%= email.subject %>
  </p>
  <p class="text-sm text-gray-500">
    <%= excerpt(email.body.to_…

One trick is that if you are using ActionText, call to_plain_text otherwise you might end up with unclosed HTML tags. In general, when you show an excerpt of rich text, you don’t want all of the formatting to be applied anyways.

Remote Ruby 

Rails for Beginners, Site Editors, and Skypack

[00:01:43] The guys chat about callbacks. 
[00:04:46] Chris tells us about the new course he did, “Ruby on Rails for Beginners.”
[00:08:58] Andrew asks Chris if he actually talked to people who are newer in Rails to figure out about the pry or if he had a sense of it because of where he’s at in the community. [00:11:57] Jason hints at wanting to make a course on SQL for Active Record for Rails Developers, which gets Chris and Andrew excited.  
[00:14:22] Chris mentions how he put up a bare bones site that needed some examples for better minitests.com.
[00:16:48] Jason spills the beans about rebuilding their site editor. Andrew wonders what specifically wasn’t working in StimulusReflex…
Awesome Ruby Newsletter 

💎 Issue 247 - Why Wasn't Ruby 3 Faster?

Scott Bartell 

Capybara Tip: Current Path Matcher

Sometimes within a Capybara test you need to verify that you are on a particular page. The obvious way to test for this is by making expectations against current_path or current_url.

The problem with this approach is that the previous action that was taken (such as a button click, or some fancy JS / History.pushState()) may not have completed when your expectation runs against current_path.

One way to address this is to add an expectation that has waiting logic built into it before the expectation against current_path:

expect(page).to have_content('Login')
expect(current_path).to eq('/login') 

An even better way to do this is to use have_current_path which has waiting/retry logic…

AkitaOnRails.com 

[Akitando] #92 - RANT de 200K! | Upgrade do meu PC

DESCRIÇÃO

Depois de 2 anos e meio chegamos aos 200 mil assinantes!!

No video de hoje vou começar com um mini-Rant só pra não perder o costume mas a maior parte do vídeo vai ser apresentando e discutindo os upgrades que eu fiz no meu PC de edição principal e porque eu escolhi determinados componentes.

Todo mundo sempre me pergunta sobre teleprompter, camera, meu setup, então hoje vou mostrar um pouco disso.

ÍNDICE:

00:00 - Intro 00:56 - Mini-Rant: os objetivos do Canal 04:48 - Organização do Conteúdo do Canal 07:11 - Bastidores: Scripts 12:01 - Bastidores: Teleprompter 12:30 - Bastidores: Câmera 12:58 - PC: Storage 13:59 - PC: SATA vs PCIe 16:08 - PC: GTX 1070 17:17 - PC: RTX…

AkitaOnRails.com 

[Akitando] #91 - Qual a REAL diferença entre Arquivos Binário e Texto?? 🤔

DESCRIÇÃO

Um arquivo texto É um binário! 😲

E como um sistema operacional diferencia entre os dois? Porque ele sabe executar um binário compilado de C, sabe executar um script de Python, mas também sabe dar erro se tentamos executar um texto qualquer?

Como isso funciona de verdade por trás dos panos?

Hoje é dia de escovar bit, e entendermos o que é ASCII, o que é ELF e muito mais!

ERRATA: - em 05:29 eu falo "porque 10 em decimal é A" mas eu quis dizer "10 em HEXAdecimal é A" - em 13:53 eu falo que depois de 69 é 70, mas tá errado, em hexa depois de 0x69 é 0x6A, depois 0x6B e assim por diante até 0x6F e só depois seria 0x70

ÍNDICE:

00:00 - Intro 01:14 - Hello World 04:30 - arquivos…