Rubyland

news, opinion, tutorials, about ruby, aggregated
Sources About
Remote Ruby 

Testing in Ruby

I said the word "RSpec" a couple of minutes in, and then we spent 40 minutes talking about testing. We talk about our separate tastes of Minitest and RSpec, TDD, JavaScript testing, and more!
JetRockets 

Activity Indicator in SwiftUI

zverok with ruby 

Fun with each_with_object and other Enumerator adventures

A short preface: I am writing in Ruby since 2004. For last 5 years I am also participating in language development, documenting new and old features, proposing some (several got accepted) and diving deep into weirdest mysteries of the language. So, I was pretty confident I’ve seen every technique for clean and DRY code with functional flavour. That was until today, my friend and fellow Rubyist Vladimir Ermilov discovered this:

Yup, this is a short, DRY, no-block-arg-names-repetition way to do this:

[1, 2, 3].zip([4, 5, 6]).map { |ary| ary.join(' ') }

….e.g. to pass…

Awesome Ruby Newsletter 

💎 Issue 178 - Debugging hidden memory leaks in Ruby

Ruby Weekly 

Debugging Hidden Memory Leaks in Ruby

#472 — October 17, 2019

Read on the Web

Ruby Weekly

Debugging Hidden Memory Leaks in Ruby — Tracking down a nasty (new with Rails 6) memory leak using tools like mwrap, heaptrack, iseq_collector, and chap. If these tools aren’t in your toolbox, they might be soon!

Sam Saffron

Shrine 3.0 Released: The File Attachment Handler — Shrine is a gem for handling file attachments that supports resumable uploads and can work with Rails and standard Rack apps. This version is even more friendly to non-Active Record frameworks, among other things.

Janko Marohnić

A New Ruby SDK Gem for Rubyists to Use the Square…

GoRails Screencasts 

Continuous Integration for Ruby on Rails with GitHub Actions

How to use GitHub Actions for Continuous Integration (CI) with Ruby on Rails
Saeloun Blog 

Ruby 2.7 adds UnboundMethod#bind_call method

Ruby supports two forms of methods:

Let’s say we have a User class.

# user.rb
class User
  def initialize(name)
    @name = name
  end

  def name
    @name
  end

  def welcome
    "Hi, #{self.name}"
  end
end
> user = User.new('John Doe')
# Bound Method
> user.method(:welcome)
#=> #<Method: User#welcome (SOME_PATH/user.rb):6>
# Unbound Method
> User.instance_method(:welcome)
#=> #<UnboundMethod: User#welcome (SOME_PATH/user.rb):6>

We can create UnboundMethod using Module#instance_method or Method#unbind and can call after binding to an object.

W…

Valentino Gagliardi 

How To Handle Exceptions in Python (vs JavaScript)

In this episode of Python for JavaScript developers: how to handle exceptions in Python, how to create your own, and how to raise them.

How To Handle Exceptions in Python (vs JavaScript)

So, you’ve been developing with JavaScript since forever and now you want to approach Python, but don’t know where to start? I’m a Python lover myself, and this series is for you.

In this episode you’ll learn how Python compares to JavaScript when it comes to handling exceptions and errors. Enjoy!

Requirements

To follow along you need at least a basic understanding of JavaScript and its quirks. This series is not an exhaustive guide to both languages, rather, a 10.000 feet comparison between them.

The complete series

Missed an…

AkitaOnRails.com 

[Akitando] #43 - Concorrência e Paralelismo (Parte 1) | Entendendo Back-End para Iniciantes (Parte 3)

De volta à série Começando aos 40, estamos já no oitavo episódio! E ela é a Parte 3 do tema de Back-end, mas desta vez vou precisar me alongar mais explicando conceitos antes de retornar às ferramentas.

Concorrência e Paralelismo é algo que todo iniciante hoje em dia já esbarra logo cedo. Nós vivemos num mundo que é naturalmente paralelo e concorrente. Já estamos no ponto onde nos definimos como "multi-tarefas".

Mesmo assim, ainda existe mais superstição e "misticismo" do que real noção do que esse conceito realmente significa. E ao contrário do que possa parecer, na realidade o básico não é tão complicado assim.

Preste bastante atenção na explicação de hoje, porque isso vai ser base…

AkitaOnRails.com 

[Akitando] #44 - Concorrência e Paralelismo (Parte 2) | Entendendo Back-end para Iniciantes (Parte 4)

Finalmente! Chegamos ao FIM do assunto sobre Concorrência e Paralelismo! Desta vez vou finalizar o que faltou falar sobre processos, threads, como eles se coordenam, quanto isso custa pro sistema operacional. E então vamos vamos sobre Green-Threads e como as linguagens modernas lidam com elas.

Então finalmente posso dar minha perspectiva sobre as linguagens interpretadas como Python, Ruby, mais sobre Erlang/Elixir, Go, e como Scala, e outras linguagens se comportam em termos de concorrência e como se comparam com coisas como Javascript.

Este é o episódio mais longo da série até agora, e se você conseguir chegar até o final deve ter uma visão bem mais completa quando for discutir sobre…

AkitaOnRails.com 

[Akitando] #45 - Gerenciamento de Memória (Parte 1) | Entendendo Back-end para Iniciantes (Parte 5)

Eu disse no episódio anterior que não sabia se ia falar sobre Gerenciamento de Memória, mas acho que não dá pra terminar a série e não falar disso. Então hoje vamos escovar bits um pouco. Como a série é pra iniciantes, vale revisitar um pouco sobre representações binárias e hexadecimal e entender mais sobre como o computador e seus programas enxergam essa tal de "memória".

Hoje quero explicar como os principais alocadores de memória do Linux funcionam e ensinar o que são os principais desafios que envolvem o gerenciamento de memória. Tudo isso vai ser importante pra semana que vem que vou explicar sobre garbage collectors.

Erratas:

  • aos 11:39 min o áudio fica ruim por 1 minuto. Eu…

AkitaOnRails.com 

[Akitando] #46 - Gerenciamento de Memória (Parte 2) | Entendendo Back-end para Iniciantes (Parte 6)

Finalmente, chegamos no último episódio do tema de Back-End!

Devo dizer que este foi um dos episódios que eu mais queria explicar. Toda nova linguagem hoje em dia tem Garbage Collector. Mas a maioria dos programadores não tem a mínima idéia de como eles funcionam.

Mais importante: todos acreditam que garbage collectors são mágicos e "simplesmente funcionam" mas não entendem quais são os reais motivos de porque eles existem, quais problemas eles resolvem, e quanto eles CUSTAM pro seu programa. Sim! Nenhuma mágica vem de graça.

Hoje vamos usar o que aprendemos até agora pra finalmente olhar linguagens como Objective-C/Swift, Python, Ruby, Java, Erlang/Elixir, Go e entender como eles…

AkitaOnRails.com 

[Akitando] #47 - Entendendo "Devops" para Iniciantes em Programação (Parte 1) | Série "Começando aos 40"

Finalmente chegamos no tema final da série! Vamos falar um pouco sobre o tal do "devops".

Esta parte meio que depende dos conceitos que vimos nos últimos episódios então se você é iniciante, e ainda não assistiu os anteriores, recomendo que faça isso.

No episódio de hoje quero dar um pouco do contexto histórico, dos anos 90 até os anos 2000, indo de configuração manual de máquinas, hospedagens compartilhadas, virtualização até os VPS. Vamos entender como uma coisa foi levando pra próxima.

Muita gente confunde muitos termos, virtualização, paravirtualização, jails, containers, hypervisors e não sabe o que é o que, então eu vou distinguir tudo pra vocês finalmente entenderem.

=== Script

AkitaOnRails.com 

[Akitando] #48 - Entendendo "Devops" para Iniciantes em Programação (Parte 2) | Série "Começando aos 40"

Hoje finalmente vamos usar tudo que aprendemos até agora pra explicar as diferenças entre hypervisors e containers, e agora sim, falar um pouco mais de Docker e Kubernetes.

Precisamos explicar o que foi essa mudança no mundo de sysadmins de ter que lidar com hardware pra um mundo onde hardware essencialmente se tornou software pra muitos casos, especialmente em Web e como empresas como a Amazon AWS e Heroku ajudaram a mudar inclusive a forma como programamos.

Links:

  • Goodbye Docker and Thanks for all the Fish (https://technodrone.blogspot.com/2019/02/goodbye-docker-and-thanks-for-all-fish.html)
  • The Twelve-Factor App (https://12factor.net)

=== Script

Olá pessoal, Fabio Akita

Este é…

AkitaOnRails.com 

[Akitando] #49 - Devo usar NOSQL? | "ENDGAME" para Iniciantes em Programação | Série "Começando aos 40"

Finalmente chegamos ao décimo-quarto e último episódio da série "Começando aos 40". E eu quis coincidir o término da série com o dia da pré-estreia de Avengers: Endgame, porque eu sou geek assim mesmo :-)

No episódio de hoje vou dar um pequeno overview sobre o que eu considero como alguns dos principais aspectos de bancos de dados relacionais, NoSQL, e as melhores escolhas pra sua aplicação.

Vou aproveitar pra complementar a discussão de máquinas virtuais, containers, IaaS, PaaS adicionando minhas opiniões sobre FaaS ou Function as a Service.

E no final quero deixar um pensamento sobre esse mundo cloud e o impacto quanto ao mundo de código livre pra todos pensarem.

Se você ainda não…

AkitaOnRails.com 

[Akitando] #50 - A Bolha de Startups vai Estourar? | Winter is Coming

Você está iniciando neste mercado de tecnologia ou está atuando nele faz menos de 10 anos.

Primeiro, quero introduzir um pouco minha filosofia do que é ser um "profissional" de desenvolvimento de software; tema que vou explorar mais nos próximos episódios.

Segundo (17:25), quero apresentar uma análise sob a ótica de quem está neste mercado desde os anos 90 e tentar explorar uma possibilidade que mais e mais está se solidificando: a de que estamos chegando ao fim de um período de bolha de tech startups.

Será que o Inverno está chegando para o mercado de tecnologia? E como você deveria se preparar se for esse o caso?

Disclaimer: tudo que estiver neste vídeo é uma opinião pessoal…

AkitaOnRails.com 

[Akitando] #59 - A História de Ruby on Rails | Por que deu certo?

15 anos atrás Ruby on Rails é lançado, e todo mundo tinha certeza que logo desapareceria.

Ruby on Rails 6.0 acabou de ser lançado.

Why, The Lucky Stiff sumiu faz 10 anos.

Estou iniciando o 2o ano do meu canal e acho que agora é uma boa hora para contar essa história.

Esta é a história que eu queria ter contado logo que comecei o canal, 1 ano atrás. Mas eu precisava explicar muitas outras histórias antes para dar contexto. Minha própria carreira inicial. A história da computação e da Web nos anos 90 a 2000. Conceitos como Agilidade e Startups.

Agora que contei boa parte do que queria, se vocês assistiram os vídeos do último ano, devem estar equipados pra entender esta parte da…

AkitaOnRails.com 

[Akitando] #58 - Aniversário de UM ANO!! | Bastidores do Canal

Finalmente!! Chegamos a 1 ANO do Canal Akitando!

Foi uma jornada incrível, absolutamente difícil, eu praticamente me coloquei na missão de fazer o equivalente a 1 palestra completa, densa e detalhada, TODA SEMANA ao longo de 1 ano inteiro!

Quero compartilhar com vocês um pouco de como eu pensei no conceito do canal, como eu produzo os vídeos e um pouquinho de bastidores.

O vídeo de hoje não tem nenhuma grande missão a não ser comemorar! Obrigado a todos vocês que acompanham o canal e espero que continuem compartilhando os vídeos pra que esse acumulado de informações consiga chegar a mais pessoas.

Continuem compartilhando os videos pra ajudar o conteúdo a chegar a mais pessoas!

==…

AkitaOnRails.com 

[Akitando] #57 - O Guia DEFINITIVO de Organizações | Desconstruindo o Modelo Spotify [RATED R]

No episódio "Esqueça Metodologias 'Ágeis'" eu critico como consultorias e coaches deturparam e prostituíram as idéia originais de agilidade.

O episódio de hoje continua na mesma idéia de como a idéia do tal "Modelo Spotify" ou "Modelo de Squads" foi também surrupiada pelos mesmos perpetradores e deturpada até o próprio Spotify não reconhecer mais.

Mas eu resolvi andar a última milha e ir além, eu quero usar o que o paper do Spotify descreve pra explicar de onde vêm conceitos como "Auto-organização", o que de fato são "organizações ágeis" e quais são todos os erros que que todas as empresas cometem quando pensam em implementar metodologias desse tipo.

O vídeo é BEM longo, e a primeira…

AkitaOnRails.com 

[Akitando] #56 - Falando um pouco de MAC, LINUX e WINDOWS | Qual eu devo escolher?

No episódio de hoje, pegando carona que eu fiz um vídeo sobre instalar ambiente de desenvolvimento em Ubuntu (https://www.youtube.com/watch?v=epiyExCyb2s) eu queria aproveitar pra contar vários pequenos momentos e conceitos sobre sistemas operacionais que eu gosto de ficar discutindo.

No geral eu poderia dizer que é um vídeo “comparando” Linux, Mac e Windows mas a idéia não é escolher um no final mas sim delinear o que aconteceu nos últimos 20 e tantos anos que me fez ficar mudando de sistemas e hardware ao longo do tempo e porque existem algumas opiniões formadas hoje que quem está só começando não consegue entender porque as recomendações são extremas em muitos casos.

Antigamente a…

AkitaOnRails.com 

[Akitando] #55 - Refletindo sobre RESOLUÇÃO de Problemas | O bug do Premiere

No episódio sobre Ubuntu pra Devs da semana passada, quem me acompanhou pelas redes sociais (que é @akitaonrails em todas) viu que eu passei por um perrengue pra conseguir editar o vídeo e isso me custou uns 2 dias de atraso. Por isso o vídeo foi entregue só na sexta-feira e eu dormi mal duas noites.

Neste vídeo quero falar duas coisas. A primeira é explicar o que aconteceu e como eu resolvi o problema, pra quem tem interesse em edição de vídeo aprender também.

A segunda coisa é usar esse episódio pra refletir sobre como eu penso sobre resolução de problemas de modo mais amplo, sobre o processo investigativo e sobre a avaliação das minhas próprias capacidades, e como vocês também podem…

AkitaOnRails.com 

[Akitando] #54 - O Guia DEFINITIVO de UBUNTU para Devs Iniciantes

No primeiro episódio técnico da série Começando aos 40 (https://www.youtube.com/watch?v=sx4hAHhO9CY) eu recomendei que todos estudassem Linux, e foi só isso. Hoje eu resolvi retomar o que eu disse e mostrar que em casa de ferreiro o espeto é de ferro!

Vou pegar um Ubuntu recém-instalado, e do zero ir até um ambiente completo para desenvolvedores de software (em particular Web, claro), com Docker, Tmux, Vim, ASDF e durante o percurso explicar várias coisas sobre Linux em geral, várias dicas, e até mesmo como customizar os temas pra ficar "dahura"!

As dicas estão espalhadas por todo o vídeo, então tente assistir o vídeo inteiro sem pular nada.

Até o momento esse deve ser o vídeo mais…

AkitaOnRails.com 

[Akitando] #53 - 10 Mitos sobre Tech Startups | Parte 2 [Rated R]

Nesta segunda e última parte do tema "10 Mitos de Tech Startups" eu vou pegar mais pesado em porque você insiste em ser enganado o tempo todo por fake-celebridades de empreendorismo de palco e o que você realmente deveria estar pensando se seu objetivo é realmente abrir uma empresa ou ajudar o mundo. Dica: não é em eventinho de startup.

E o episódio de hoje é RATED R de novo porque eu acho que vai doer em muito floquinho. Se for frágil, pegue seus sais antes de assistir. Mas assista!

Links:

  • 10 Mitos de Tech Startups | PARTE 1 (https://www.youtube.com/watch?v=jkHnPxsiyGk)

  • Somos Matematicamente Ignorantes…

AkitaOnRails.com 

[Akitando] #52 - 10 Mitos sobre Tech Startups | Parte 1

errata: no começo do vídeo eu falo "positivismo" mas na realidade queria dizer "otimismo". não tem nada a ver com a filosofia.

O tema de hoje vai ser dividido em 2 episódios. Vamos cobrir os primeiros 5 mitos dos 10 sobre Tech Startups e continuamos o resto na semana que vem.

Desta vez eu resolvi pegar uma palestra que apresentei nos últimos anos chamado "Desmistificando Mitos de Startups" e adaptei pro formato de video do canal, depois digam se gostaram disso.

Infelizmente até hoje ainda repetem muitos mantras e dogmas errados e muitos jovens estão perdendo tempo seguindo as celebridades de "empreendedorismo de palco" e o objetivo de hoje é quebrar esses dogmas.

Links:

  • A Brief…
AkitaOnRails.com 

[Akitando] #51 - Esqueça Metodologias "Ágeis" | [Rated R]

Finalmente, resolvi tocar num assunto divertido: o lamentável estado atual do mundo do "Ágil".

A intenção é contrabalancear a exuberância irracional dos vendedores de "Ágil" como se fosse a sétima maravilha da humanidade. TL;DR não é.

Também foi uma boa desculpa para eu adicionar trechos da entrevista que fiz com Robert Martin (em 2010!)

O recado é muito simples: não existe bala de prata. Agilidade não são processos, metodologias, nem a miríade de numerologia e astrologia que assola este mercado. É hora de recuperar um pouco da essência original do mundo da Agilidade.

Se você ficou deprimido com o video (sorry) eu já tinha publicado alguns videos que podem te dar uma luz de caminhos…

Ruby on Rails Podcast 

291: New Gigs, Rails 6 Upgrade Confessions and Rubyconf Hype

Brittany and Nick catch up on happenings in their worlds. Nick started a new gig and Brittany was accepted into Rubyconf as a speaker. Predictably, after discussing upgrading to Rails 6 and releasing new gems, the conversation focused on keyboards.

Links for this episode:

Brought to you by:

Kensington

Kensington's Universal Docking Stations give you access to more…

Saeloun Blog 

Rails 6 adds delete_by and destroy_by methods.

Rails has provided methods like find_by, find_or_initialize_by, and find_or_create_by to fetch, initialize, and create record respectivley, based on the passed conditions.

Similar method to delete or destroy records was missing in Rails.

As per this issue, Rails 6 has introduced two methods delete_by and destroy_by to ActiveRecord::Relation, which deletes or destroys all the records that match the passed conditions.

Before Rails 6:

Deleting or destroying records was executed as shown below:

User.where(is_active: false).delete_all
User.where(is_active: false).destroy_all

In Rails 6:

Rails 6 now provides convenience methods to achieve the same. The above examples can now be achieved…

BigBinary Blog 

Rails 6 raises ArgumentError if custom param contains a colon

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

The :param option in routes is used to override default resource identifier i.e. :id.

Let’s take for an example that we want product :name to be as the default resource identifier instead of :id while defining routes for products. In this case, :param option comes handy. We will see below how we can use this option.

Before Rails 6, if resource custom param contains a colon, Rails used to consider that as an extra param which should not be the case because it sneaks in an extra param.

An issue was raised in Aug, 2017 which was later fixed in February this year.

So, now Rails 6 raises ArgumentError if a resource…

The Bike Shed 

218: Finesse in Quitting (Brittany Martin)

On this week's episode, Steph is joined by Brittany Martin, an avid Rubyist and the host of the Ruby on Rails Podcast. They discuss Brittany's passion for roller derby and her upcoming Ruby conference talk: "Hire Me, I'm Excellent at Quitting." They also discuss using AWS Serverless, troubleshooting Postgress connection errors and working with Google Pay and Apple Wallet to introduce digital tickets.

All Ruby Podcasts by Devchat.tv 

RR 434: Surviving Webpack with Ross Kaffenberger

Ross Kaffenberger is a software engineer at Stitch Fix and has been developing web applications for the past 12 years, mostly in Ruby and JavaScript. Today he and the panel are discussing how to survive Webpack. When many folks first encounter Webpack, they feel confused, overwhelmed, and don’t know how to get it to do what you want it to. In the latest version they tried to introduce some more sane default settings, but it is still a major change in technology. 

Ross talks about how his company transitioned Rails 5 to Rails 6 with the new Webpacker. His company chose to take an iterative approach and slowly migrated to Webpacker. His app was very JS heavy with a large number of libraries,…

Sam Saffron 

Debugging hidden memory leaks in Ruby

In 2015 I wrote about some of the tooling Ruby provides for diagnosing managed memory leaks. The article mostly focused on the easy managed leaks.

This article covers tools and tricks you can use to attack leaks that you can not easily introspect in Ruby. In particular I will discuss mwrap, heaptrack, iseq_collector and chap.

An unmanaged memory leak

This little program leaks memory by calling malloc directly. It starts off consuming 16MB and finishes off consuming 118MB of RSS. The code allocates 100k blocks of 1024 bytes and de-allocates 50 thousand of them.


require 'fiddle'
require 'objspace'

def usage
  rss = `ps -p #{Process.pid} -o rss -h`.strip.to_i *…
Test Double | Our Blog 

Let's hash this out.

Ruby hashes are wonderfully versatile. You can store any kind of object using any kind of key and do all sorts of wacky and magical things. Hashes bring joy. Odes have been written to the wonderful "hashrocket" (Ruby's affectionate name for the => operator).

But in our day to day work, we don't see a lot of this:

{ [2, 3, 4] => 1.82343 }

More often, we see this:

{ name: "Steve" }

The latter is a natural fit for most data - this attribute has this value. So simple! But not so long ago (cough, 12 years), Rubyists used this syntax: { :name => "Steve" }. This matches nicely to { "name" => "Steve" }, and describes the same thing. So symmetrical. Strings, symbols, pick whatever you want.…

Prathamesh Sonpatki 

Cross domain session sharing in Rails - Part 1

We have multiple micro services at Memory.ai which talk to each other and share data. As we are extracting more and more micro services, we were facing the problem of adding authentication layer in every service. In an ideal world, only one service would perform the authentication and other services will just delegate the authentication to that service.

If you have carefully seen how Google authenticates you, you would have noticed that just signing into GMail, Google also signs you in YouTube, Google maps and all the other Google applications. You might not be aware of it but that's what Google does.

We wanted to achieve something similar where logging in one application means you don't have…

Valentino Gagliardi 

Making friends with optional chaining in TypeScript

Nested property access can be tricky in JavaScript, leading to long chains of &&. Learn how to use optional chaining for cleaning up your code.

Making Friend With Optional Chaining in TypeScript

To be honest I never jump on newest JavaScript proposals so fast. If it’s not at least at stage 3 most of the times I gloss over. But if the new feature is implemented in TypeScript then I know it’s going to be good.

That’s exactly the case with optional chaining in TypeScript. It will land into JavaScript and it’s already available in TypeScript beta.

Setting up TypeScript

First things first create a new project and install TypeScript beta:

mkdir optional_chaining_ts && cd $_

npm init -y

npm i typescript@beta

Next up…

Janko’s Blog 

Shrine 3.0 Released

I’ve just released version 3.0 of Shrine, a gem for handling file attachments in Ruby applications. It’s been months of hard work, but I feel it’s finally ready.

Redesigned website

The old Jekyll website has been rewritten to use Docusaurus. :sparkles:

Shrine new website

Docusaurus gives us nice features such as sidebars with autogenerated TOC and related documents, which greatly improve navigation experience.

Shrine website sidebars

We also now have a snippet switcher, which makes it easier to show code for different libraries.

Shrine website snippet switcher A Shrine website snippet switcher B Shrine website snippet switcher C

Once our request for Algolia DocSearch gets approved, we’ll have searchable documentation as well. :mag:

Major features

I’ve talked about the major changes in more detail Upcoming…

RubyGuides 

How to Use Scopes in Ruby on Rails

What is a scope in Rails & why is it useful?

Well…

Scopes are custom queries that you define inside your Rails models with the scope method.

Every scope takes two arguments:

  1. A name, which you use to call this scope in your code
  2. A lambda, which implements the query

It looks like this:

class Fruit < ApplicationRecord
  scope :with_juice, -> { where("juice > 0") }
end

As a result of calling a scope, you’ll get an ActiveRecord::Relation object.

Which means you can chain & combine scopes!

Example:

Fruit.with_juice.with_round_shape.first(3)

Now:

There’s more to learn about Rails scopes, so let’s keep exploring the topic.

When To Use Scopes?

Ok, scopes are cool, but when should you use them?

Valentino Gagliardi 

Code Documentation And Static Typing in Python (vs JavaScript)

Another episode of Python For JavaScript Developers, a series of side-by-side between Python and JavaScript. In this installment: code documentation and static typing in Python.

Code Documentation And Static Typing in Python (vs JavaScript)

You’re a JavaScript developer, you want to know how to document and add static types in Python before jumping in. Are you? If so, this article is spot on. Enjoy!

In this episode:

  • Code Documentation with reStructuredText
  • Gradual typing with reStructuredText
  • Static typing in Python with mypy

Requirements

To follow along you need at least a basic understanding of JavaScript and a bit of “types” theory. If you don’t know what a type is check out Python data types and then come back!

Later in the…

Valentino Gagliardi 

Membership And Instance Operators in Python (vs JavaScript)

Python For JavaScript Developers is a series of side-by-side comparisons between Python and JavaScript. In this episode: membership and instance operators in Python (vs JavaScript).

Python For JavaScript Developers: Membership And Instance Operators

So, you’ve been developing with JavaScript since forever and now you want to approach Python, but don’t know where to start? This series is for you. In this episode you’ll learn how Python compares to JavaScript when it comes to membership and instance operators. Enjoy!

Python For JavaScript Developers: requirements

To follow along you need at least a basic understanding of JavaScript and its quirks. This series is not an exhaustive guide to both languages, rather, a 10.000 feet comparison…

You…

Valentino Gagliardi 

Python Data Types: Strings, Numbers, and Complex Types (vs JavaScript)

New episode of Python For JavaScript Developers, a series of side-by-side comparisons between Python and JavaScript. In this installment: Python data types.

Python For JavaScript Developers: Python Data Types

This series is a hitchhiker guide to Python for JavaScript developers, wrote as a reference while training other fellow devs, and as a note for my future self. Enjoy!

In this episode:

  • Basic data types: string, number, boolean
  • Complex data types: dictionary, list, tuple, set

Python For JavaScript Developers: requirements

To follow along you need at least a basic understanding of JavaScript and its quirks. This series is not an exhaustive guide to both languages, rather, a 10.000 feet comparison between them.

You…

Valentino Gagliardi 

Arithmetic, Logical, And Comparison Operators in Python (vs JavaScript)

First installment of Python For JavaScript Developers, a series of side-by-side between Python and JavaScript. In this episode: arithmetic, logical, and comparison operators in Python (vs JavaScript).

Python For JavaScript Developers: Arithmetic And Comparison

JavaScript is my bread and butter, but I don’t dislike other programming languages, at all. In fact I always had a crush for Python which I used over the years ranging from scripts to API applications with Flask and Django.

This series is a hitchhiker guide to Python for JavaScript developers, wrote as a reference while training other fellow devs, and as a note for my future self. Enjoy!

In this episode:

  • Arithmetic operators
  • Increment and decrement
  • Comparison operators
  • Logica…

Requirements

To follow along you need at…

Saeloun Blog 

Ruby adds Array#intersection method

Taking cue from Array#union and Array#difference methods added to Ruby 2.6, Ruby has now added Array#intersection method which is an alias for Array#&.

The purpose behind these additions is to make the methods more clean and readable than their operator counterparts.

Lets take a look at what each method does,

Array#intersection

The Array#intersection method returns a new array containing elements common to both arrays. The order is preserved from original array. Since its a set operation, the resultant array has unique elements.

[ 1, 1, 3, 5 ].intersection([ 3, 2, 1 ]) #=> [ 1, 3 ]
[ "a" ].intersection #=> [ "a" ]

You can also pass multiple arrays as arguments to the method,

[ "a", "…
Remote Ruby 

Catching Up

After two weeks off, we took some time to sit down and talk. We chat about Chris' experience with SCA while updating Pay, upcoming HatchBox updates, Jason's mini side project, and enjoy some other banter.
EquiValent 

Retry ActiveJob (Sidekiq) on exception

Let say we have a simple Ruby on Rails ActiveJob background job that would do something in a Background. For example

# app/jobs/new_work_published_job.rb
class NotifyThatWorkWasPublishedJob < ActiveJob::Base
  queue_as :notifications

  def perform(work_id:)
    work = Work.find_by!(id: work_id)

    # ...some logic that will send Email, Push notification etc.
  end
end

# trigger
work = Work.create(title: 'hello', author_email: 'foo@bar.eu')
NotifyThatWorkWasPublishedJob.perform_later(work_id: work.id)

Now there are many things that can go wrong when doing architecture with background jobs.

Sometimes you may be dealing with a situation where Jobs will get queued and triggered to…

OmbuLabs Blog 

Implementing Stripe Connect in Rails: Part 2

Some time ago we wrote an article to explain how to implement Stripe Connect in a Rails application. That article covered mainly the connection part between Rails and Stripe. This one will cover the fun part, which is making transactions, charges, refunds, and more.

If you haven't checked out the first part yet I recommend you do so since this article will continue from where that one ended.

Frontend

Before diving into the Stripe API, one of the first things that you should implement is a form that captures the payment information (e.g. credit card). The simplest way to do this is using Stripe Checkout, but if you want a more customizable version you can use Stripe Elements. I…

Appfolio Engineering 

How MJIT Generates C From Ruby - A Deep Dive

You probably already know the basics of JIT in Ruby. CRuby’s JIT implementation, called MJIT, is a really interesting beast.

But what does the C code actually look like? How is it generated? What are all the specifics?

If you’re afraid of looking at C code, this may be a good week to skip this blog. I’m just sayin’.

How Ruby Runs Your Code

I’ll give you the short version here: Ruby parses your code. It turns it into an Abstract Syntax Tree, which is just a tree-data-structure version of the operations you asked it to do. Before Ruby 1.9, Ruby would directly interpret the tree structure to run your code. Current Ruby (1.9 through 2.6-ish) translates it into buffers of bytecodes. These buffers…

Awesome Ruby Newsletter 

💎 Issue 177 - Ruby 2.7 deprecates automatic conversion from a hash to keyword arguments

Prathamesh Sonpatki 

prepend_before_action in Rails

Rails encourages usage of callbacks in controllers to execute common pieces of  code before or after an action. A very simple example of this is calling the authenticate_user! method from Devise before every action to make sure that user is authenticated.

class ApplicationController < ActionController::Base
  before_action :authenticate_user!
end

But what if you want to execute a different piece of code before calling authenticate_user!? I wanted to set a cookie based on whether the request was coming from mobile app or from web before calling authenticate_user!. The most important thing was I wanted to set the cookie only for a particular controller action.

class MagicAuthController <…
JetRockets 

How quickly and easily run a local server with fake api data (mocks)?

Depfu 

Depfu for GitLab

If you’re using GitLab and were wondering if automated dependency updates could work for your team or project, I have good news for you: Depfu fully supports GitLab now!

Here are the details:

If you’re using gitlab.com

If you’re using any of the SaaS plans from GitLab, free or paid, you can now use Depfu by simply signing up, connecting with your GitLab account and selecting which repos you want to run on. Our login and signup lets you choose between GitLab or Github, like you’re used from other services.

Unfortuntely, similar to Github before they released Github Apps, the API permissions and scopes on GitLab are not as granular as we would like them to be for our use case. Here is…

Ruby Weekly 

Why RSpec Tests Fail (and How To Fix Them)

#471 — October 10, 2019

Read on the Web

Ruby Weekly

Ruby 2.7 to Deprecate Automatic Conversion of a Hash to Keyword Arguments — The way ‘keyword arguments’ work in Ruby grew from the legacy approach of passing a hash of arguments into methods. Ruby 3.0, however, will have ‘real’ keyword arguments separated from the idea of hashes, so the automatic conversion of a supplied hash into keyword arguments will yield a warning in Ruby 2.7.

Rohit Kumar

The Minitest Style Guide — The Rubocop team have put together a style guide for at least my favorite Ruby testing library of choice: minitest!

Rubocop Team

P…

JetRockets 

Double splat arguments in Crystal

Saeloun Blog 

Rails 6 adds support for multi environment credentials

Background

Generally in applications there are various secrets and credentials, that we need to make use of like API keys, secrets, etc. For such secrets we need the ability to conveniently and securely manage credentials.

Rails 5.1 added a feature to use secrets to manage credentials.

Rails 5.2 replaced secrets with credentials, since encrypted and un-encrypted secrets were making it harder to manage them.

A set of files were used to manage these credentials:

  • config/credentials.yml.enc
  • config/master.key

config/credentials.yml.enc is an encrypted file which store the credentials. As this is a encrypted file, we can safely commit it to our version control systems.

config/…

Semaphore 

Lyft Software Engineer on the Future of Envoy

In today’s Semaphore Uncut episode, I’m speaking with Matt Klein, a software engineer at Lyft. Matt is the architect behind Lyft’s Envoy, one of the most popular open-source service proxies, which is shipping out a new mobile version soon.

What prompted Matt and the team at Lyft to create Envoy, and what’s next for the open-source application? Listen to the episode to find out the answers to these questions and more. Then, check out some of our favorite parts of the conversation in the episode highlights below.

You can also get Semaphore Uncut on Apple Podcasts, Spotify, Google Podcasts, Stitcher, and more.

Like this episode? Be sure to leave a ⭐️⭐️⭐️⭐️⭐️ review on the…

GoRails Screencasts 

How to write System Tests in Rails

System tests allow you to use a browser for testing your Rails app including Javascript
Ruby on Rails Podcast 

290: Ruby for Good with Polly Schandorf

Polly Schandorf is a Ruby community advocate, a newly minted extreme programmer and an organizer for Ruby for Good. She is also one of the organizers of WeCamp - a code retreat and unconference in the woods in the suburbs of DC. Help Ruby for Good do the good they are trying to do!

Links for this episode:

Ruby Inside - Medium 

JSON in Rails behind the scenes

It can be hard to understand concepts like ‘meta-programming’ without seeing a real world example first. In this post, we’ll do exactly that.

Jbuilder utilizes Ruby’s meta-programming ideas to create any json structure imaginable. It’s amazing once you discover how it actually works. And how it achieves that with a beautiful builder-style DSL (Domain Specific Language). Let’s jump in.

Let’s create a basic JSON structure with Jbuilder in order to understand how it works:

json.name 'liroy'
json.age '31'

Which will produce the following json:

{
"name": "liroy",
"age" : "31"
}

But what’s really interesting is that json doesn’t have a name or age method. So how come it doesn’t raise a NoMethodError…

RubyMine Blog 

Find usages in RubyMine

Find usages can be used to find all the pieces of code referencing a specific element, such as a class, method, symbol, or many of the others. RubyMine can also find dynamic usages, including Rails associations, factories, or delegates. You have the ability to specify the scope and search through an open file, project, referenced libraries, and so on.
Find usages is very helpful for investigating a project and refactoring your code. For example, the Rename refactoring requires high accuracy when finding usages for a target element, so that you can trust the IDE when making such changes.
In this blog post, we’ll show you how to show usages of an element in the editor or separate window,…

Semaphore 

A Step-by-Step Guide to Continuous Deployment on Kubernetes

A long time ago, in a job far, far away, I was tasked with switching our old-school LAMP stacks over to Kubernetes. My boss at the time, always starry-eyed for new technologies, announced the change should only take a few days—a bold statement considering we didn’t even have a grasp on how containers worked yet.

After reading the official docs and Googling around, I began to feel overwhelmed. There were too many new concepts to learn: there were the pods, the containers, and the replicas. To me, it seemed Kubernetes was reserved for a clique of sophisticated developers.

I then did what I always do in these cases: I learned by doing. Going through a simple example goes a long way in…

JetRockets 

Save your links from phishers.

On the Edge of Ruby 

A New Expectation Syntax for ruby/spec

ruby/spec is a test suite for the behavior of the Ruby programming language. The utility to run the test suite is called MSpec and is very similar to RSpec 2.

The reason to have its own runner and not simply using RSpec is that MSpec is significantly simpler than RSpec 2. For example, it does not require any standard library. Early-stage Ruby implementations typically do not support the entire standard library, but based on the simplicity of MSpec they are still able to run language and core library specs with minimal efforts.

MSpec also provides a few features that RSpec does or did not have such as automatically tagging/untagging failing specs, various guards useful for ruby/spec, etc.

Code with Jason 

My general approach to Rails testing

My development workflow

The code I write is influenced by certain factors upstream of the code itself.

Before I start coding a feature, I like to do everything I can to try to ensure that the user story I’m working on is small and that it’s crisply defined. By small, I mean not more than a day’s worth of work. By crisply defined, I mean that the user story includes a reasonably precise and detailed description of what the scope of that…

Honeybadger Developer Blog 

Configure Your App with SSM Parameter Store

Configuring your Rails app via environment variables works well, but sometimes you want to be able to update your configuration on the fly. Here's a way to update your app's environment using SSM Parameter Store.

Why would you want to do this? Well, say you deploy your Rails app to an EC2 instance that's part of an autoscaling group. To get the fastest boot times, you should create a custom AMI with your code already on it (a.k.a. a golden image) that the autoscaling group can use when it's time to boot a new instance. Unfortunately, if you store your configuration on the image (and use something like dotenv to load it), you'll need to create a new AMI every time you have a configuration…

Semaphore 

Visual Workflow Builder: Build CI/CD Pipelines Without Writing YAML

We’re excited to announce the availability of Workflow Builder, a visual tool that lets you build serverless CI/CD pipelines on Semaphore without writing YAML.

Configuring a CI/CD pipeline using Semaphore Workflow Builder.

Our mission at Semaphore is to make CI/CD simple so that you can focus more on developing features for your users. To that end, earlier this year we introduced complex pipeline workflows and custom Docker container-based agents. Along came many smaller improvements such as global job configuration, parallelism, and a common DSL for defining conditions for pipeline block execution, promotions and fast-failing.

The love/hate relationship with YAML

Modeling…

Valentino Gagliardi 

Code Documentation for JavaScript With JSDoc: An Introduction

Writing documentation for the source code can help your future self and your colleagues. Learn how to document JavaScript with JSDoc!

Code Documentation for JavaScript With JSDoc: An Introduction

Why code documentation?

Suppose you wrote a couple of functions for making an HTML table with JavaScript. You could use those function right now, or pass them to another developer.

Everything is clear in your mind the moment you write the code, yet a month later you don’t remember how to use functionA or functionB anymore. And so your colleagues. How functionA is supposed to be called? What parameters it takes? And what shape should the parameters have?

Code documentation dissolves those doubts, helping you and other developers to underst…

All Ruby Podcasts by Devchat.tv 

MRS 099: Joe Leo

Joe Leo joins Charles Max Wood on this week's My Ruby Story. Joe is the Founder and CEO of the agile software consultancy, Def Method. He shares his journey as a developer. Joe was tutored by his uncle and learned how to code in Basic on a command line. He wanted to be in the music industry and liked math.

Joe is currently working on holistic product development and is delving into areas such as what makes a good product manager and what makes a good product design. Charles and Joe talk about difficulties in quantifying good product management skills or writing tests and other non-coding aspects that surround making a product.

Host: Charles Max Wood

Joined by Special Guest: Joe Leo

Spon…

All Ruby Podcasts by Devchat.tv 

RR 433: ShipLane with John Epperson

John Epperson has been doing ruby for 12 years and is a friend of Andrew Mason. He got into Docker a couple years ago and felt like something was missing, so he wrote Shiplane. He liked Docker because it was a promise that he could delegate a lot of the manual devops work to something else, and that something else was able to automate all of it. What he noticed was if you have a Docker thing in development and want to transfer it into production, there was no clear path to get a Docker item from development to production. The process wasn’t truly automated, so he created ShipLane in an attempt to automate it.

ShipLane solves this problem by assuming that you have a box out there, whether…

BigBinary Blog 

Rails 6 introduces new code loader called Zeitwerk

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

Zeitwerk is the new code loader that comes with Rails 6 by default. In addition to providing autoloading, eager loading, and reloading capabilities, it also improves the classical code loader by being efficient and thread safe. According to the author of Zeitwerk, Xavier Noria, one of the main motivations for writing Zeitwerk was to keep code DRY and to remove the brittle require calls.

Zeitwerk is available as a gem with no additional dependencies. It means any regular Ruby project can use Zeitwerk.

How to use Zeitwerk

Zeitwerk is baked in a Rails 6 project, thanks to the Zeitwerk-Rails integration. For a…

The Bike Shed 

217: A Vote For Reasonableness

On this week's episode, Steph shares an update on her mechanical keyboard adventures and provides a summary for the Ruby pipeline operator being reverted. Chris gets Steph's opinion on a possible improvement around using materialized views in tests and describes a recent debugging adventure he and Steph went on. They also discuss a listener question regarding encouraging companies to use Ruby and Rails and asking how we identify ourselves as developers. Finally, they round out the conversation with a clarification around public vs private GraphQL APIs.

If you're…

Test Double | Our Blog 

Much Ado About Bike Sheds, Part III

This is the third post in a series of our takes on bike shedding. After understanding the origin story and how we might lose our empathy in our crusade against bike shedding can we still glean anything valuable from the infamous bike shed?

You're probably reading this post because you feel like there's some room for improvement on your team. As a Test Double agent, I relish the opportunity to don my detective hat and magnifying glass. Please join me on this journey. This topic runs deep and wide, encompassing pretty much the entire field of behavioral science—in which I am not an expert!

I have, however, been on a lot of teams that each had their share of strengths and blind spots. I often…

Saeloun Blog 

Distance calculation in Ruby using RGeo - Geospatial library for Ruby

RGeo is a gem for writing location-based applications in Ruby programming language.

It is used to:

  • Represent spatial and geolocation data objects such as points, lines, and polygons.
  • Perform standard spatial analysis operations such as finding intersections, creating buffers, and computing lengths and areas.
  • Correctly handle spherical geometry, and compute geographic projections for map display and data analysis.
  • Read and write location data in the WKT and WKB representations used by spatial databases.

Prerequisites:

  • Rails app.
  • PostgreSQL database with PostGIS extension enabled.
  • rgeo gem.
  • activerecord-postgis-adapter gem.

Installing the rgeo gem:

Before we install…

OmbuLabs Blog 

Manual Testing: How to become a better tester of your own code

Manual testing is a necessary part of software development and quality assurance. And although it's important to have a dedicated tester in your team, you as a developer can also help speed up QA, and thus the software development process, by becoming a better manual tester of your own code.

But how to do that? I'll cover 4 simple points that will help you get there!

Manual testing is a necessary part of software development and quality assurance. It’s true that it is prone to errors, after all, every human activity is, and can also be time-consuming and boring. It’s also true that automated testing reduces testing time a great deal and is more reliable. But automated tests can only go…

RubyGuides 

Ruby Syntax Reference For Beginners

Learning Ruby can be overwhelming with all the bits & pieces you have to remember.

That’s why I put together this syntax reference for you!

It will help refresh your memory & quickly review what you need to know to write Ruby programs.

Have fun!

Strings

A string is a sequence of characters inside two quotation marks (""). Used to represent text & data.

Example:

"I like chocolate"

Another option is to use single quotation marks ('').

'Ruby is awesome'

Important methods:

  • size
  • empty?
  • include?
  • gsub
  • split

More methods:

https://www.rubyguides.com/2018/01/ruby-string-methods/

Hashes

A hash ({}) is a key-value pair (a => b) data structure. Used as a dictionary. You can access hash elements…

Scott Watermasysk 

Dank Mono

I switched1 my main programming font last week from Fira Code 2 to Dank Mono.

After a couple of days, I have to say I am enjoying it.

  1. The italic crossed with script (cursive) is a nice visual change.
  2. Supports ligatures which is now a must have for me.
  3. There are two types of developers. Those who love change and those who hate change. Neither are right or wrong, but I am in the love change camp. The small visual update makes everything feel more fresh.

The recommended font-size with it is 14. I had been running Fira Code (which I still love) at 24px. For Dank I switched to 20px and bumped the font-weight up to 500 in Visual Studio Code.

  1. Check out if you want to see…

RubyMine Blog 

Running Rails tasks with Run Anything

Hi there!

As you may already know, RubyMine provides a unified way to run Ruby scripts, Rails applications, Rake tasks, Rails generators, and so on with the powerful Run Anything (double Ctrl). At the same time, you can run Rails generators and Rake tasks using dedicated popups. For example, you can run the desired Rake task by pressing ⌥R / Ctrl+Alt+R and then finding the required action:
Rake tasks popup

This is similar too for Rails generators ⌥⌘G / Ctrl+Alt+G:
Rails generators popup

Starting with v2019.3, we have decided to replace the older popups with Run Anything and provide a single point of entry for running tasks/generators. So now, pressing ⌥R / Ctrl+Alt+R invokes the Run Anything popup and adds the rake command…

Martian Chronicles, Evil Martians’ team blog 

Images done right: Web graphics, good to the last byte

Authors: Polina Gurtovaya, Front-end Developer at Evil Martians, Rita Klubochkina, Front-end Developer at Evil Martians, and Andy Barnov, Writer at Evil Martians. Teacher at Le Wagon

Start taking graphics on the web seriously and boost your applications’ performance by learning the essentials about image formats, both modern and old-school. Dig into SVGs and adopt the latest and greatest tools to optimize your graphical content: both vector and raster. Study the theory behind digital images and how humans perceive them—to improve the experience for your users.

Did you know that the average web page destined for a desktop in 2019 takes 2MB of traffic, and half of everything that a web…

Drifting Ruby Screencasts 

Ruby on Rails Tips and Tricks

Ruby and Ruby on Rails tricks from, dot files, operators, bundling, StimulusJS and more.
Riding Rails 

New attribute methods, regex matching and more!

Hello! Tim here with the latest scoop on Ruby on Rails!

New *_previously_was attribute methods!

Your models just got a sprinkling of a little extra sugar. For any given attribute that changed, you can now do:

Model.attribute_previously_was # => previous value

Support for matches_regex in MySQL

Check out this PR for a great example of how you can now perform regular expression matching on your MySQL queries!

Preservation of join order fixed

This fix managed to take down a number of open issues in one go! It addresses a recent regression by ensuring that the order of any user-supplied joins will be preserved as far as Active Record is able to do so.

28 people contributed to Rails…

Saeloun Blog 

Ruby 2.7 deprecates automatic conversion from a hash to keyword arguments

The method definition in Ruby is extremely flexible. The example from Marc-André Lafortune blog sums it up nicely.

class C
  def hi(needed, needed2,
         maybe1 = "42", maybe2 = maybe1.upcase,
         *args,
         named1: 'hello', named2: a_method(named1, needed2),
         **options,
         &block)
  end
end

C.instance_method(:hi).parameters
# => [ [:req, :needed], [:req, :needed2],
#      [:opt, :maybe1], [:opt, :maybe2],
#      [:rest, :args],
#      [:key, :named1], [:key, :named2],
#      [:keyrest, :options],
#      [:block, :block] ]

Ruby 2.7 will bring in certain changes to the keyword arguments design, but first, let’s understand what are keyword arguments?

What are…

Code with Jason 

The difference between domains, domain models, object models and domain objects

I recently came across a question regarding the difference between domains and domain models. These terms probably mean different things to different people, but I’ll define the terms as I use them.

Domain

When I’m working on a software project, the domain is the conceptual area I’m working inside of. For example, if I’m working on an application that has to do with restaurants, the domain is restaurants.

Domain model

The world is a staggeringly complex place. Even relatively simple-seeming things like restaurants involve way more complexity than could be accurately captured in a software system. So instead of coding to a domain, we have to code to a domain model.

For me, a domain model is…

With a Twist 

Development/Production parity for Rails Internationalization

To support both English and Spanish in web apps, we can use Ruby’s I18n library, which allows for easy translations through YAML files for each language. If a translation is missing, ideally we’d like to see an error in our tests, which makes the test suite fail. However, if our development environment is not set up to raise exceptions, there could be bugs lurking, or waiting to be introduced.

One such instance happened to us recently, because our I18n.backend (yes, that’s a thing!) in Rails was different in the development/testing and production environments. Development used the “base” i18n backend, while production was set up to use the “fallbacks” backend.

This difference made it so…

Pat Shaughnessy 

How Rust Makes Error Handling Part of the Language


In Spanish these are all “dedos,” while in English
we can distinguish between fingers and toes.

Learning a foreign language can be an incredible experience, not only because you can talk to new people, visit new countries, read new books, etc. When you learn the words someone from a different culture uses, you start to see things from their perspective. You understand the way they think a bit more.

The same is true for programming languages. Learning the syntax, keywords and patterns of a new programming language enables you to think about problems from a different perspective. You learn to solve problems in a different way.

I’ve been studying Rust recently, a new programming language…

Giant Robots Smashing Into Other Giant Robots 

Meowifier: A Hiss-tory Lesson

The worldwide sensation (and eventual flaming pile of 💩) Game of Thrones premiered in the year of our Lord Stark 2011. If you’re anything like me, you would look forward to Sunday evenings – settling into your sofa with your three cats and/or significant other, waiting for the opening credits to start at 8pm CST (I was living in Omaha, Nebraska at the time). There would be so much excitement building up, but no way to release it and the opening credits are soooo long. Like, one-minute-and-37-seconds long. So I released my pent-up energy the best way I knew how – meowing along to the melody of the Game of Thrones theme song at the top of my lungs with my cats and/or significant other looking…

Awesome Ruby Newsletter 

💎 Issue 176 - Ruby 2.7 Experimental Features in Production: Pattern matching and numbered block args

Code with Jason 

Why I don’t like Dokku

In the process of building and talking about Exosuit, my tool to make AWS-Rails deployment easier, the question has come up a couple times: “Have you heard about Dokku?”

I’ve seen Dokku but I don’t want to use it. There are two reasons. First, I don’t want to have to involve Docker. (More precisely, I don’t want to make my Exosuit users have to involve Docker.) Second, I find Dokku aesthetically repulsive. I’ll explain what I mean by “aesthetically repulsive”.

Here are the installation instructions from the Dokku docs:

$ wget https://raw.githubusercontent.com/dokku/dokku/v0.18.3/bootstrap.sh
$ sudo DOKKU_TAG=v0.18.3 bash bootstrap.sh

Yuck. What’s all this raw.githubusercontent.com stuff?…

Julia Evans 

SQL queries don't start with SELECT

Okay, obviously many SQL queries do start with SELECT (and actually this post is only about SELECT queries, not INSERTs or anything).

But! Yesterday I was working on an explanation of window functions, and I found myself googling “can you filter based on the result of a window function”. As in – can you filter the result of a window function in a WHERE or HAVING or something?

Eventually I concluded “window functions must run after WHERE and GROUP BY happen, so you can’t do it”. But this led me to a bigger question – what order do SQL queries actually run in?.

This was something that I felt like I knew intuitively (“I’ve written at least 10,000 SQL queries, some of them were really…

Ruby Weekly 

Using Ruby for primitive but productive automation

#470 — October 3, 2019

Read on the Web

Ruby Weekly

What's New in IRB in Ruby 2.7? — IRB, the trusty Ruby REPL, isn’t something we often see getting updated with new Ruby releases, but Ruby 2.7 is introducing a few niceties like syntax highlighting. Pry may, however, remain the power user’s REPL of choice.

Prajakta Tambe

Ruby 2.6.5 Released (and 2.5.7, and 2.4.9) — Security update time. These fixed security issues are unlikely to affect many in a direct way but include a code injection vulnerability in Shell#[], two issues with WEBrick, and a NUL (ASCII 0) injection vulnerability in two File methods.…

ruby-lang.org

dry-rb news 

Introducing dry-effects

Today we're introducing another gem and supercharging our toolset: say hello to dry-effects!

dry-effects is an implementation of algebraic effects in Ruby. Sound scary? Fear not! After a few examples, it'll feel very natural and compelling.

Struggling with side effects

Writing purely functional code can be an attractive idea; it makes your code robust, testable, ... and useless! Indeed, if code doesn't perform any side effects, such as reading/writing data to the disc or network communications, the only thing it actually does is heating the CPU. On the other hand, side effects remove determinism from the code, making testing challenging. Here come…

Saeloun Blog 

Ruby 2.7 adds Enumerator::Lazy#eager

Enumerator::Lazy

Back in Ruby 2.0 added Enumerator::Lazy that allowed chaining of multiple operations to be performed on collection without evaluating them immediately, instead it evaluates only when its needed or forced to.

This allows us to perform operations on long or potentially infinite sequences and chain multiple operations without generating intermediate arrays.

2.5.3 :001 > prime_lazy = (2..Float::INFINITY).lazy.reject{|i| (2..Math.sqrt(i)).any?{|j| i % j == 0 } }
 => #<Enumerator::Lazy: #<Enumerator::Lazy: 2..Infinity>:reject>
 
2.5.3 :002 > prime_lazy = prime_lazy.select {|n| n > 100}
 => #<Enumerator::Lazy: #<Enumerator::Lazy: #<Enumerator::Lazy: 2..Infinity>:reject>:select>
…
Ruby on Rails Podcast 

289: When You HTTParty, You Must Party Hard with John Nunemaker

John Nunemaker, creator and maintainer of HTTParty and Flipper, regaled Brittany with tales of why he loves Ruby & Rails, his change of mindset on being an open source maintainer and how a post-install hook can inspire even the most grumpy of developers.

Links for this episode:

Brought to you by:

Hoefler&Co

A good font is one of the best ways to make your project…

Ruby News 

Ruby 2.4.9 Released

Ruby 2.4.9 has been released.

This release is a re-package of 2.4.8 because the previous Ruby 2.4.8 release tarball does not install. (See [Bug #16197] in detail.) There are no essential change except their version numbers between 2.4.8 and 2.4.9.

Ruby 2.4 is now under the state of the security maintenance phase, until the end of March of 2020. After that date, maintenance of Ruby 2.4 will be ended. We recommend you start planning the migration to newer versions of Ruby, such as 2.6 or 2.5.

Download

Julia Evans 

Zine revenue for 2019

I occasionally get questions like “Can you share what you’ve learned about running a business?” The most surprising thing I’ve learned is that it’s possible to make money by teaching people computer things on the internet, so I want to make that a little more concrete by sharing the revenue from the zine business so far in 2019. Here’s a graph of revenue by month (the last month is September 2019):

This adds up to $87,858 USD for 2019 so far, which (depending on what I release in the rest of this year) is on track to be similar to revenue for 2018 ($101,558).

Until quite recently I’d been writing zines in my spare time, and now I’m taking a year to focus on it.

how $30,000 for…

RubyGuides 

How to Use The Ruby Ternary Operator (?:)

What is a ternary operator in Ruby?

A ternary operator is made of three parts, that’s where the word “ternary” comes from. These parts include a conditional statement & two possible outcomes.

In other words, a ternary gives you a way to write a compact if/else expression in just one line of code.

For example:

if apple_stock > 1
  :eat_apple
else
  :buy_apple
end

Can become this:

apple_stock > 1 ? :eat_apple : :buy_apple

Thanks to the ternary operator!

Question…

How does this work, exactly & what is the proper syntax?

Let’s find out.

A Template For Writing Your Own Ternary

If we generalize the syntax for a ternary operator you get a “fill in the blanks” kind of template.

It looks like…

Test Double | Our Blog 

Much Ado About Bike Sheds, Part II

This is the second of a series of blog posts about bike sheds. In part one, we explored the history of the bike shed story, you can read part one here.

Why do software developers find so much resonance in the bike shed story?

What's important? What's really important? How do you know it's important? How do you know whether this thing is more or less important than that thing?

Parkinson mined a great deal of satire from what he saw as a kind of logical puzzle—looking at the costs, the committee, he suggests, ought to have spent more time on higher price-tag proposals as opposed to dwelling on relatively minor line items, like a bike shed or coffee budget.

So, is that the lesson we should…

Ruby News 

CVE-2019-16255: A code injection vulnerability of Shell#[] and Shell#test

A code injection vulnerability of Shell#[] and Shell#test in a standard library (lib/shell.rb) was found. The vulnerability has been assigned the CVE identifier CVE-2019-16255.

Details

Shell#[] and its alias Shell#test defined in lib/shell.rb allow code injection if the first argument (aka the “command” argument) is untrusted data. An attacker can exploit this to call an arbitrary Ruby method.

Note that passing untrusted data to methods of Shell is dangerous in general. Users must never do it. However, we treat this particular case as a vulnerability because the purpose of Shell#[] and Shell#test is considered file testing.

All users running an affected release should upgrade…

Ruby News 

CVE-2019-16254: HTTP response splitting in WEBrick (Additional fix)

There is an HTTP response splitting vulnerability in WEBrick bundled with Ruby. This vulnerability has been assigned the CVE identifier CVE-2019-16254.

Details

If a program using WEBrick inserts untrusted input into the response header, an attacker can exploit it to insert a newline character to split a header, and inject malicious content to deceive clients.

This is the same issue as CVE-2017-17742. The previous fix was incomplete, which addressed the CRLF vector, but did not address an isolated CR or an isolated LF.

All users running an affected release should upgrade immediately.

Affected Versions

  • All releases that are Ruby 2.3 or earlier
  • Ruby 2.4 series: Ruby 2.4.7 or earlier
Ruby News 

CVE-2019-15845: A NUL injection vulnerability of File.fnmatch and File.fnmatch?

A NUL injection vulnerability of Ruby built-in methods (File.fnmatch and File.fnmatch?) was found. An attacker who has the control of the path pattern parameter could exploit this vulnerability to make path matching pass despite the intention of the program author. CVE-2019-15845 has been assigned to this vulnerability.

Details

Built-in methods File.fnmatch and its alias File.fnmatch? accept the path pattern as their first parameter. When the pattern contains NUL character (\0), the methods recognize that the path pattern ends immediately before the NUL byte. Therefore, a script that uses an external input as the pattern argument, an attacker can make it wrongly match a pathname that…

Al…

Ruby News 

Ruby 2.4.8 Released

Ruby 2.4.8 has been released.

This release includes security fixes. Please check the topics below for details.

Ruby 2.4 is now under the state of the security maintenance phase, until the end of March of 2020. After that date, maintenance of Ruby 2.4 will be ended. We recommend you start planning the migration to newer versions of Ruby, such as 2.6 or…

Ruby News 

Ruby 2.5.7 Released

Ruby 2.5.7 has been released.

This release includes security fixes as listed below. Please check the topics below for details.

See the commit log for details.

Download

Ruby News 

Ruby 2.6.5 Released

Ruby 2.6.5 has been released.

This release includes security fixes. Please check the topics below for details.

See the commit logs for changes in detail.

Download

Ruby News 

CVE-2019-16201: Regular Expression Denial of Service vulnerability of WEBrick's Digest access authentication

Regular expression denial of service vulnerability of WEBrick’s Digest authentication module was found. An attacker can exploit this vulnerability to cause an effective denial of service against a WEBrick service.

CVE-2019-16201 has been assigned to this vulnerability.

All users running any affected releases should upgrade as soon as possible.

Affected Versions

  • All releases that are Ruby 2.3 or earlier
  • Ruby 2.4 series: Ruby 2.4.7 or earlier
  • Ruby 2.5 series: Ruby 2.5.6 or earlier
  • Ruby 2.6 series: Ruby 2.6.4 or earlier
  • Ruby 2.7.0-preview1
  • prior to master commit 36e057e26ef2104bc2349799d6c52d22bb1c7d03

Acknowledgement

Thanks to 358 for discovering this issue.

History

All Ruby Podcasts by Devchat.tv 

MRS 098: David A. Black

David A. Black, Software Engineer IV at 2U, joins Charles Max Wood on this week's My Ruby Story. David A. Black has been a Ruby user for 19 years and has been writing books about Ruby for the last 14 years as well as organizing conferences.

David has been coding since he was 13 years old. He was introduced to Ruby in November 2000 when he was looking at the computer section at the old bookstore Borders and picked up the book Programming Ruby by Dave Thomas and Andy Hunt. Five years later, David, who has a Ph.D. in Cinema Studies from New York University, resigned from a tenured professorship in the communication field to become a full-time programmer, trainer, and author. His book The…

All Ruby Podcasts by Devchat.tv 

RR 432: Stop Testing, Start Storytelling with Mike Schutte

Mike Schutte is a fronted developer at TED conferences and was trained in code school at Turing in Colorado. He likes the idea of code as a communication tool, and in 2018 he gave a talk at RailsConf called Stop Testing. Start Storytelling. 

Today the panel is discussing what Mike means by storytelling in testing. In order to combat the hesitancy to start testing, Mike believes that changing your mindset to think away from the implementation details while deploying these tests can help them be more efficient. In short, if the test isn’t readable by a non-developer, then it’s not telling a story, it’s just writing code. The test is almost the first point of contact away from the source…

BigBinary Blog 

Rails 6 adds ActiveSupport::ActionableError

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

When working in a team on a Rails application, we often bump into PendingMigrationError or other errors that need us to run a rails command, rake task etc.

Rails introduced a way to resolve such frequent errors in development from error page itself.

Rails 6 added ActiveSupport::ActionableError module to define actions we want perform on errors, right from the error page.

For example, this is how PendingMigrationError page looks like in Rails 6.

How Actionable error looks like in Rails 6

By default, a button is added on error screen that says Run pending migrations. Clicking on this button would dispatch rails db:migrate action. Page will reload once…

We can also…

The Bike Shed 

216: I'm Not the Best Criminal

On this week's episode, Steph recounts an issue with an email client that lowercases URLs and Chris ponders the art of logging and using structured logs. They also highlight a plugin that improves TypeScript support in Vim, how the Pinterest team celebrates the "retirement" of code, and respond to a listener who is debating between refactoring their app or investing in a full rewrite.

If you're enjoying The Bike Shed, we'd love it if you could give it a rating or review on iTunes. Thanks!

Saeloun Blog 

Rails 6.1 adds HTTP Feature Policy

What is Feature Policy?

Feature Policy allows us to control the behavior of certain web APIs and features in the browser. We can specify which APIs are to be disabled or enabled for a given list of origins.

Feature Policy provides two ways to do this:

  • Feature-Policy HTTP header
Feature-Policy: camera 'none' 

Feature-Policy: payment 'self' 'https://example.com'
  • allow attribute on iframes (Not supported by this change)
<iframe src='https://example.com' allow='fullscreen'></iframe> 

<iframe src='https://example.com' allow='geolocation *'></iframe>

Google Dev Blog, has an in-depth article explaining this functionality in detail.

Why should we use it?

It allows us to enforce…

Saeloun Blog 

Rails 6 introduces Action Text to provide WYSIWYG support in Rails

This is part one of our multipart series exploring Action Text.

Before

Before introduction to Action Text, adding support for rich-text fields, or WYSIWYG editors was cumbersome. We would choose from several available options like TinyMCE, Trix, and so on. After adding this in views, support to handle file uploads, storage of text and converting back and forth from view vs database, supporting plugins, etc on the backend, were some of the repetitive tasks we would spend time on.

Action Text

Action Text is a new framework introduced as part of Rails 6 that makes it easy to work with rich text content.

Action Text combines Trix Editor, Active Storage, and ActiveRecord to…

Super Good Software 

Solidus Conf 2019 Is Coming Up

Solidus Conf 2019 is only three weeks away. From October 21st to 24th, you’ll find the Solidus community gathered in Salt Lake City, Utah for two days of conference talks and two days of hack days. If you’re at all a part of the Solidus ecosystem, you’ll want to be there.

Salt Lake City itself has a lot to offer, but that’s not why you should go. Whether you’re running a store yourself, building and maintaining stores for others, or working on the services that power eCommerce, our annual conference always has something for everyone.

Every year the speakers deliver talks showcasing impressive new possibilities for the platform, exciting new extensions, and strategies for building the best…

Julia Evans 

Notes on building SQL exercises

In the last couple of weeks I’ve been working on some interactive SQL exercises to help people get better at writing SQL queries. This is a pretty new thing for me so I thought I’d write a few notes about my process so far!

why SQL is exciting: distributed SQL engines

To me the reason why SQL is exciting is that a lot of companies are storing their data in distributed SQL databases (Google BigQuery, Amazon Redshift, Spark SQL, Presto, etc) that let you run a complicated query across a billion rows pretty quickly! They’re fast partly because they’re designed to run your query across possibly tens or hundreds of computers.

At my last job I wrote thousands of SQL queries to do data…

Semaphore 

iOS CI/CD: Continuous Integration and Continuous Delivery Explained

Continuous integration and continuous delivery (CI/CD) is widely used by development teams, even in open-source communities. It offers a sustainable way to test and deploy code many times a day without the hurdle of doing it manually.

In this guide, you’ll learn the foundations of getting started with CI/CD for iOS. We’ll learn about:

  1. The importance of CI/CD for iOS developers
  2. Principles of iOS CI/CD
  3. The top benefits of CI/CD for iOS
  4. Best practices to remember for iOS CI/CD
  5. An iOS CI/CD workflow example
  6. Getting started with CI/CD for iOS
  7. Choosing the right iOS CI/CD platform

By the end of this article, you’ll be able to evaluate your current workflow, adopt the best CI/CD practices, and…

Code with Jason 

How I wrote a command-line Ruby program to manage EC2 instances for me

Why I did this

Heroku is great, but not in 100% of cases

When I want to quickly deploy a Rails application, my go-to choice is Heroku. I’m a big fan of the idea that I can just run heroku create and have a production application online in just a matter of seconds.

Unfortunately, Heroku isn’t always a desirable option. If I’m just messing around, I don’t usually want to pay for Heroku features, but I also don’t always want my dynos to fall asleep after 30 minutes like on the free tier. (I’m aware that there are ways around this but I don’t necessarily want to deal with the hassle of all that.)

Also, sometimes I want finer control than what Heroku provides. I want to be “closer to the metal”…