Rubyland

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

Intern Experience at Appfolio

My experience at Appfolio for the past 5 months has been nothing short of amazing. TL;DR - I've made more friends and participated in more 'extra-curricular' activities than my other two internships combined. If beautiful weather 24/7, programming in paradise, biking, rock climbing, D&D, dancing, or Disney World catch your fancy, read on.

# Day 1

My mentor greeted me at the door with a peach flavored smoothie to welcome me to the team. Everyone I passed by on my first day said 'hi' or waved to all us new hires on our morning tour. My computer already had most of the necessary technologies installed, and I was ready to start programming immediately! Appfolio has a well-organized onboarding…

Ruby Weekly 

Ruby roots, Stripe's approach to testing, and the 'ambiguous' operator

#476 — November 14, 2019

Read on the Web

Ruby Weekly

Ruby's Roots and Matz's Leadership — Noah summarizes a recent talk Ruby’s creator, Matz, gave about the history of Ruby, where he got various language feature ideas from, and what he thinks Ruby’s greatest invention was (psst.. blocks!)

Noah Gibbs

The Delegation Challenge of Ruby 2.7 — This is a somewhat odd situation where a change to arguments changes delegation so things are handled differently in Ruby 2.6, 2.7, and 3.0. It’s a tough nut to crack and a great example of language design related edge cases.

Benoit Daloze

Happy Rails…

Semaphore 

In Continuous Integration, Run Fast and Fundamental Tests First

While it’s great to keep your entire CI/CD pipeline fast, on many occasions you don’t even need to run all tests to get the feedback you need.

Unit tests run the fastest, because they test a very small piece of code in complete isolation from the rest of the system. For example, they usually don’t touch the database.

Unit tests deal with fundamental business logic, and are the most numerous, as is commonly depicted in the “test pyramid” diagram:

test pyramidTest pyramid

A failure in unit tests is a sign of a fundamental problem, which makes running the remaining high-level and long-running tests irrelevant.

For these reasons, projects with test suites that run for anything longer than a…

GoRails Screencasts 

How to Test Background Jobs with Active Job

Learn how to test Active Job in your Ruby on Rails application
EquiValent 

RSpec mocks in Rails native tests (minitest)

I love RSpec but recently I’ve decided to build sideproject with 100% Rails 6 vanilla environment (that means no extra gems, just what is inside Rails 6, including the Minitest test environment)

Problem is Minitest stubs and mocks suuuucks !

If you are interested in Minitest mocks check this article

So I want to use Rails Minitest but RSpec mocks and this is how:

# Gemfile

# ...

group :test do
  # ...
  gem 'rspec-mocks'
end

# ...

note, no rails-rspec is not required

# test/test_helper

# ...
require 'rspec/mocks/minitest_integration'
# ...

require 'test_helper'

class AddPhoneControllerTest < ActionDispatch::IntegrationTest
  test 'POST create add phone to inzerat when…
Ruby on Rails Podcast 

295: Power the World with Rails with Bindiya Mansharamani & Andrew Derenge

Bindiya Mansharamani, Director of Engineering, & Andrew Derenge, Principal Engineer at RigUp joined Brittany to discuss RigUp's GraphQL design choices, engineering culture and the career path to achieve senior and director level.

Links for this episode:

Brought to you by:

Mirror Placement

If you are a Rails developer currently in the market, a startup seeking to grow your team, or just simply curious to hear about market and salary trends, Brian at Mirror Placement would love to chat with you. He will send you a turkey!

You can reach him at…

avdi.codes 

Exploring, Pathmaking, Traveling

Lately Jess and I have been talking about the work of software development, particularly project setup.

Some of the work that we do when is purely experimental. “What happens when I push this button?” “What sub-commands are available?” “What is possible with this library?” “Will this fix it?” That’s exploring.

Exploring can be aimless. It can also be deliberate. We can make hypotheses and prove or disprove them. “I don't understand this framework, but I hypothesize that a change to this file will be be reflected in the UI”. This kind of code science can help us build a model: a limited theory of how software works.

This is like looking at the map and saying “I think that I'm here,…

Saeloun Blog 

Handling attachments in Action Text in Rails 6

This is part two of our multipart series exploring Action Text, In part 1, we looked at basic of how we can get started with providing WYSIWYG support in our Apps using ActionText.

This blog post will deal with file attachments in Action Text.

Quick setup

We have discussed setup steps in Part 1. Here we will just list a set of commands to setup a new rails app and enable Action Text which one can execute so as to follow along this post.

Create a new rails app:

$ rails new blog_app --database=postgresql

Switch to app directory:

$ cd blog_app

Create database:

$ rails db:create

Enable support for action_text:

$ rails action_text:install
$ rails db:migrate

Add scaffold for post…

Saeloun Blog 

Rails 6 adds Purpose Metadata to Cookies

Action Dispatch provides cookies.signed and cookies.encrypted, which can be used to prevent users from tampering with a cookie’s value.

Example:

# Prevents users from tampering with this cookie’s value
cookies.signed[:proxy_id] = current_admin.id

# Resultant client side cookie's content
# MTAx--fd47225e9e6de0710a4f84104d73fec1e4d94c65

# Prevents users from reading and tampering with its value
cookies.encrypted[:current_zip] = current_user.zip

# Resultant client side cookie's content
# aHNzb2dxVkN1bE1MQTd0MnFsSkZ2dz09LS1tM2NHcVZQbjRoT0RVOVdvdE9FdHZnPT0%3D--be007d00dda3678f79fda9d2a7bcfacc6a760919

The problem

Before Rails 6, the methods described above only signed the content of…

All Ruby Podcasts by Devchat.tv 

RR 437: Deploying Rails Onto Kubernetes with Khash Sajadi

Khash and Kasia works for Cloud 66, a company started in 2012 with a goal to make Rails deployment simple and infrastructure easy to understand for application developers. As the company has moved towards containerization, they have integrated with Kubernetes. Khash talks about what distinguishes Cloud 66 from other platform as a service companies and why the company was started. He begins by talking about the structure of Heroku, how they own the entire stack down to the server, and how they are bound to a data center. Cloud 66 differs because they decided to break that unit economy from a data center to a server, so they don’t own the entire stack. Instead, they deploy what looks like an…

The Bike Shed 

222: That Eureka Moment

On this week's episode, Steph and Chris dive into the world of crafting pull requests for optimal code review, as well as the flip side of providing code review. How can we make it easy for reviewers, and as reviewers, how can we make it easy for our teammates to incorporate our suggestions?

They also discuss the world of testing, from integration to visual to unit testing, and some of the tools an practices they use at each level.

Lastly, they discuss Steph's continued pairing adventures and possibly finding her max on the pairing front, a quick update on mechanical keyboards, and Steph shares a teaser of an upcoming workshop she'll be hosting around how to stay agile when building…

Test Double | Our Blog 

Downloading Large Heroku Postgres Backups

Easily one of my favorite things about developing apps with Heroku is its bevy of console commands that make it easy to manage Postgres databases. Recently, however, as one of my apps crossed the threshold from a small “hobby” tier database to a larger “standard” database, the heroku CLI started warning me that several of my favorite commands could risk degrading the database’s performance and its availability to my production application.
Saeloun Blog 

Rails 6 - Action Mailbox tryout

There are cases when application receives large number of inbound emails. And if we have to process those emails, then one has to go through each email in order to perform operations.

Let’s consider a use case of HR domain. An organization has sent an email asking candidates to submit resumes for an opening. All candidates are replying to this email with their resumes as attachments. Now, we need to upload these resumes to cloud and create a database entry for each resume.

Steps to achieve this:

  1. We’ll go through each mail.
  2. We’ll download the resume.
  3. Now, we’ll upload the resume to cloud and create entry in the resume table.

It looks like a tedious task.

Introducing Action…

Scott Watermasysk 

Limiting the Number of Posts in an Eleventy Collection

I have been working on migrating my blog over to Eleventy (hence the lack of posts recently).

As soon as I flipped the switch on the newish site, Zapier kindly notified me that way more data was being processed than before (279 posts).

First, wow, great feature by Zapier. I love they are protecting you from doing something silly (and one click continue if this was done on purpose).

Next, it was time to limit the number of posts in the feeds. I figured there would be a limit filter or query option, but as far as I could tell, one does not exist. Bummer. Then it dawned on me, everything in Eleventy is just JavaScript. With this in mind, a simple slice on a custom collection and we are in…

bogdanvlviv / Bogdan 

Rails Girls Lviv - 2019-12-07

Rails Girls - Get started with tech.

Our aim is to give tools and a community for women to understand technology and to build their ideas. We do this by providing a great experience on building things and by making technology more approachable.

Learn sketching, prototyping, basic programming and get introduced to the world of technology. Rails Girls was born in Finland, but is nowadays a global, non-profit volunteer community.

Links:

RubyGuides 

What Everyone Should Know About Fibers in Ruby

If you want to get the most performance out of your Ruby projects we have to explore fibers & how they work.

Let’s start with a simple question…

What are fibers?

Fibers are workers, they run code & keep track of their own progress. In other words, fibers are a concurrency mechanism.

Yes!

Just like threads. With the difference that you have more control over fibers than threads.

In what sense you have more control?

Well.

Your operating system decides when to run threads & when to pause them.

That’s not the case with fibers!

You have to tell a fiber exactly when to run & when to stop.

Fibers vs Threads

Threads feel like they’re running in the background, doing their thing.

Fibers don’t to…

On the Edge of Ruby 

The Delegation Challenge of Ruby 2.7

Ruby 3.0 will introduce the separation between positional and keyword arguments. The upcoming Ruby 2.7 release aims to introduce warnings for every argument behavior that will change in Ruby 3.0 to ease migration. However, delegation that works for Ruby 2.6, 2.7 and 3 seems a hard problem to solve.

What will change for arguments in Ruby 3?

From Ruby 2.0 until Ruby 2.6, keyword arguments in method definitions such as def m(kwreq:, kwopt: 42, **kwrest) are basically just syntactic sugar for extracting values from a Hash passed in last position.

This however leads to some issues when keyword arguments are mixed with optional = default or *rest arguments. For instance, should def m(opt = 42,…

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

Slides: Elixir & Phoenix – Fast, Concurrent and Explicit (Øredev)

I had the great pleasure to finally speak at Øredev! I wanted to speak there for so long, not only because it’s a great conference but also because it’s in the city of Malmö. A city that I quite like and a city I’m happy to have friends in 🙂 Anyhow, all went well although […]
RubySec 

Prototype Pollution in Chartkick.js 3.1.x

Honeybadger Developer Blog 

FounderQuest Podcast | Should You Blow Up Your Backlog?

What the heck is FounderQuest and what is it doing on the Honeybadger blog?

FounderQuest is a weekly podcast recorded and produced by the founders of Honeybadger, Ben, Starr, and Josh (these guys). It covers a wide range of topics centered around their experiences bootstrapping and running Honeybadger. Many of the topics covered on this blog overlap with the podcast discussions so if you want more Honeybadger in your life (seriously who wouldn't) then it's probably worth a listen. You can access the entire back catalog here.

On this week's episode of FounderQuest the guys weigh in on a recent debate sparked by Jason Fried at Basecamp around the value of backlogs. In short, Fried…

Appfolio Engineering 

Ruby's Roots and Matz's Leadership

I recently had the excellent fortune to be invited to a gathering at CookPad in Bristol, where Matz, Koichi, Yusuke Endoh (a.k.a. Mame) and Aaron Patterson all gave great talks about Ruby.

I was especially interested in Matz’s first talk, which was about where he got inspiration for various Ruby features, and about how he leads the language - how and why new features are added to Ruby.

You can find plenty of online speculation about where Ruby is going and how it’s managed. And I feel awkward adding to that speculation — especially since I have great respect for Matz’s leadership. But it seems reasonable to relay his own words about how he chooses.

And I love hearing about how Ruby got where…

Test Double | Our Blog 

A Model View Controller Pattern for React

React is an amazing library. Over the last 5 years it has transformed the landscape of frontend development and spawned an incredible ecosystem of tools, libraries, and patterns. Over that time, React has changed quite a bit.
Test Double | Our Blog 

A Model View Controller Pattern for React

Introduction React is an amazing library. Over the last 5 years it has transformed the landscape of frontend development and spawned an incredible ecosystem of tools, libraries, and patterns. Over that time, React has changed quite a bit.
Hi, we're Arkency 

Unexpected benefits of storing commands

You probably know that Rails Event Store, like the name suggests, is meant to store events. Commands are a different concept, but they’re very similar in structure - after all it’s just a set of attributes. So in one of our projects we slightly abused RES and made it store commands alongside with events.

You can achieve command storage in RES in different ways, with varying levels of sophistication. The most naive way to do it (just to move along with our story) would be to store an “event” named CommandIssued with command_type && command_data attributes:

class CommandIssued < RailsEventStore::Event
end

event_store.publish(CommandIssued.new(data: {
  command_type: command_type,
  comm…

We’re thinking about supporting command…

Awesome Ruby Newsletter 

💎 Issue 181 - The hidden cost of the Ruby 2.7 dot-colon method reference usage

Schneems - Programming Practices, Performance, and Pedantry 

Why does my App's Memory Use Grow Over Time?

Why on earth does my memory consumption chart look like that? It’s a question I hear every week. To help answer that question, I wrote a Web server request simulator to model how Ruby uses memory over time, though it applies to other languages as well. We will use the output of that project to dissect why a web app’s memory would be expected to look like this:

Ruby Weekly 

An interview with GitHub's Eileen Uchitelle

#475 — November 7th, 2019

Read on the Web

💬 This week we've got another interview for you — check out the bottom of the issue.

Ruby Weekly

How Ruby Really Uses Memory: On the Web and Beyond — Ruby’s memory allocation algorithm is not quite what you might think. As you add threads, considering the per-thread and across-all-threads impacts are necessary to get a firm picture of what is happening.

Richard Schneeman

Try the Fastest CI/CD Solution for Free — Faster CI/CD means greater productivity for your team and a better experience for your users. Automate your CI/CD pipeline with Semaphore to release 2x…

Sem…

Schneems - Programming Practices, Performance, and Pedantry 

How Ruby REALLY uses Memory: On the Web and Beyond

I wrote How Ruby uses Memory over four years ago, but there continue to be many misunderstandings about Ruby’s memory behavior. In this post, I will use a simulated multi-threaded webserver to show how different memory allocation patterns behave. Together we can work through the memory behavior that many developers struggle to understand.

Ruby on Rails Podcast 

294: The Career Advice I Wish I Had with Ali Spittel

Ali Spittel loves teaching people to code. She blogs a lot about code and her life as a developer. Brittany and Ali discuss the lessons behind Ali's blog post, "The Career Advice I Wish I Had".

Links for this episode:

Brought to you by:

Kensington

Kensington's Universal Docking Stations give you access to more ports so your slim Chromebook can be as powerful as a Desktop.…

Riding Rails 

Rails 6.0.1 released

Hi everyone,

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

CHANGES since 6.0.0

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.0.1 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…

BigBinary Blog 

Rails 6 adds guard against DNS Rebinding attacks

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

In a DNS Rebinding attack, a malicious webpage runs client-side script when it is loaded, to attack endpoints within a given network.

What is DNS Rebinding attack?

DNS Rebinding can be summarized as follows.

  • An unsuspecting victim is tricked into loading rebinding.network which is resolved by a DNS server controlled by a malicious entity.
  • Victims web browser sends a DNS query and gets the real IP address, say 24.56.78.99 of http://rebinding.network. This DNS server also sets a very short TTL value ( say 1 second ) on the response so that the client won’t cache this response for long.
  • The script on this…
Semaphore 

Benchmark Report: Docker Builds with Semaphore vs. Docker Hub

How many things feel as unproductive as waiting for a build? Not a lot of them I think. Docker build is a hungry beast; not only for computing resources but also for precious minutes of our lives.

What should we do about it? To find the answer, I benchmarked Semaphore and Docker Hub with a real use case scenario. I found that I can build my image at least 7 times faster on Semaphore. Read on to find out how I did it.

Continuous Integration: 10 Minutes or Bust

We’re not doing proper continuous integration unless our commit takes less than 10 minutes to build. Any longer than that and the integration feedback loop breaks down. Teams with slow pipelines merge fewer times a day,…

All Ruby Podcasts by Devchat.tv 

RR 436: Determining Pricing with Michael Herold

Michael Herold is married to an economist and is a staff engineer at Flywheel where he writes Ruby programs to support PHP programs. He gave a talk at RailsConf 2018 about how to price a product. The frame for the problem is whenever you have a business idea, you eventually have to decide how to price it, and the pricing area is ripe for inefficiency on both customer and business ends. In his talk, he gave a simple framework based on the field of market research that helps give you an idea of what to price your product or service at called the Van Westendorp Price Sensitivity Meter, which is based off of talking with your customers about how they would value your product. He explains the…

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

How to Hide AWS EC2 Instances from Network Scanning Bots using IPv6

Every server instance with publicly facing IP address is constantly targeted by malicious network scanning bots. Those bots are usually harmless but they can always start a DDoS attack or discover a vulnerability. Additionally, they are obfuscating the SSH access logs and using up some of the server resources. In this tutorial, I will explain how to hide your AWS EC2 server from those scanners using IPv6. Internet Protocol version 6 addresses range is ~7.9×1028 times larger than IPv4, so in practice, it’s currently not targeted by bots.

We’ll deep dive into AWS VPC and security groups configuration to limit SSH access to IPv6 clients only. Some knowledge of AWS is required to complete this…

Martian Chronicles, Evil Martians’ team blog 

Persisted queries in GraphQL: Slim down Apollo requests to your Ruby application

Author: Dmitry Tsepelev, Back-end Developer at Evil Martians

Learn how to reduce the size of network requests from the Apollo client in the front-end to the GraphQL Ruby back-end with the help of persisted queries. In this article, we will show how these queries work and set them up both on a client and a server with the help of our graphql-ruby-persisted_queries Ruby gem.

One of the benefits of using GraphQL is its flexibility: back-end describes the data model using types, so front-end can only get the data it needs. The problem is that the amount of data required to render a page in a real-world application can be significant, and the query to fetch this data will get out of hand…

The Bike Shed 

221: An Informed Opinion

On this week's episode, Chris and Steph catch up on recent client adventures, revisit their feelings on using let in rspec, and spend a bit of time outside their respective comfort zones. There's also some talk about nearly full-time pairing, mechanical keyboards, debugging thorny datetime issues, and how we interact with our developer tools and workflows.

This episode of The Bike Shed is sponsored by Honeybadger.

If you're enjoying The Bike Shed, we'd love it if you could give it a rating or…

Prathamesh Sonpatki 

Cross domain session sharing in Rails - Part 2

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.

In the first part of this blog series, we saw how Rails and Devise use cookies and session to authenticate the user. In this post, we will see how to share the cookies and session between multiple Rails apps.

Earlier our authentication logic was part of app.kittens.io. But when we started working on a new app - dev.kittens.io, we didn't want…

Test Double | Our Blog 

A Model View Controller Pattern for React

Introduction

React is an amazing library. Over the last 5 years it has transformed the landscape of frontend development and spawned an incredible ecosystem of tools, libraries, and patterns. Over that time, React has changed quite a bit. As React has evolved, so too have our applications, tools, and approaches.

This year (2019), React went through one of its biggest changes with React v16.8: The One With Hooks. Combined with the official Context API in v16.3, this update dropped a grenade into the React world. As developers like Kent C. Dodds pointed out, complex state management became something that any React developer could implement—without bringing in tools like Redux, MobX, or Apollo.

OmbuLabs Blog 

Roll your own Docker containers (part 2)

The last time we looked at Docker, we looked at the most basic and easy version of using it - building an image from a base image, a parent, and then layering additions and changes on top of it. With a carefully chosen base image, this can be an extremely flexible and relatively straightforward way of getting an image up and running in a container.

But what if you don't need or want a base image? Sometimes, you need the utmost control over the contents of your image, either because of security concerns or perhaps because of storage or memory constraints. Sometimes what you really need is to add your own dependencies and absolutely nothing else to a blank image. You do this by…

Saeloun Blog 

Rails 6 - Active Storage changes

Active Storage was introduced in Rails 5.2. In Rails 6, there are enhancements done to Active Storage.

Let’s explore them.

mini_magick replaced by image_processing gem

In Rails 5.2, Active Storage was using mini_magick to handle image resizing (variants).

In Rails 6, a new gem called image_processing is used by default to handle image variants. (commit)

The image_processing gem has below advantages:

  • New methods #resize_to_fit, #resize_to_fill, etc also sharpens the thumbnail after resizing.
  • It fixes the image orientation automatically. This can be referred here.
  • It provides another backend libvips that has significantly better performance than ImageMagick. With ImageMagick,…
Kir Shatrov 

Finding a memory leak in a Go app with cgo bindings

In this post, I’d like to share a story how my team was able to find and fix a memory leak in a Go app that’s been using a leaking C extension through cgo.

Usually, finding a leak in Go apps is rather trivial thanks to the built-in profiling tool that comes with Go. go tool pprof with a minimum setup steps will show you all recent allocations and the overview of the memory heap. Our case turned out to be a lot more interesting.

At work, we have an internal service discovery application written in Go and backed by Zookeeper. Zookeeper is great as a distributed configuration store, but its protocol is quite complex, so we have a REST API wrapper in Go on top of it to make it easy to consume…

Riding Rails 

Reestablish previous connection, duplicate cached values and run inline jobs

Hello! This is Roque bringing the latest news from the Rails community.

Reestablish connection to previous database after migrating

The migrate task iterates and establish a connection over each database. That resulted in the last connection being used by subsequent rake tasks. This fix will restore the previous connection before the migrate task had started.

Duplicate the cached value before writing to the local cache

This fixed the following issue:

my_string = "foo"
cache.write('key', my_string)
my_string << "bar"
cache.read('key') # => "foobar"

Run inline jobs in separate threads

Run inline jobs in separate threads so that thread locals (e.g. current attributes) are properly…

Drifting Ruby Screencasts 

Plugging in AnyCable

ActionCable can handle quite a bit of traffic, but it gets to a point where it can become a burden on the server. With AnyCable, we can not only handle more traffic, but it is also lighter on the resources.
Andy Croll 

Use GitHub Actions for Rails CI with Postgres 11 & structure.sql

This article is a follow-up to Using GitHub Actions for Rails CI with Postgres.

A little extra configuration is required to run your tests against PostgreSQL 11 if you dump your database schema as SQL, i.e. use structure.sql rather than schema.rb.

.github/workflows/tests.yml

name: Rails Tests using structure.sql

on:
  pull_request:
    branches:
      - 'master'
  push:
    branches:
      - 'master'

jobs:
  build:
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres:11.5
        ports: ["5432:5432"]
        options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5

    steps:
    - uses: actions/checkout@v1

    - name: 
Andy Croll 

Use GitHub Actions for Rails CI with Postgres

Writing tests alongside your software is strongly recommended. It helps you protect against bugs, reduces the fear of scary deploys, and can even help you develop better software.

The Ruby and Rails community have always had a strong focus on testing. Typically that means having some sort of “continuous integration” system constantly running your test suite.

There’s a bunch of good choices, but recently GitHub launched Actions (in beta), which lets you run arbitrary workflows, including tests, after certain things happen within your git repository.

Instead of…

…using a separate CI service,

Use…

…GitHub Actions to run your Rails tests.

.github/workflows/tests.yml

name: Rails Tests

on
Andy Croll 

Use GitHub Actions for Rails CI with specific Ruby versions

This article is a follow-up to Using GitHub Actions for Rails CI with Postgres.

You’ll need to add extra steps to test against versions of Ruby not supported natively by GitHub Actions. This template uses rvm to install the version of Ruby specified in your .ruby-version file.

I’m indebted to the rubygems repository for demonstrating the simplest way to do this.

.github/workflows/tests.yml

name: Rails Tests with custom Ruby version

on:
  pull_request:
    branches:
      - 'master'
  push:
    branches:
      - 'master'

jobs:
  build:
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres:11.5
        ports: ["5432:5432"]
        options: --health-cmd…
Awesome Ruby Newsletter 

💎 Issue 180 - HTTPX: A Ruby HTTP library for tomorrow... and beyond!

Riding Rails 

Rails 6.0.1 RC1 released

Hi everyone,

I am happy to announce that Rails 6.0.1.rc1 has been released.

If no regressions are found, expect the final release on Tuesday, November 5, 2019. If you find one, please open an issue on GitHub so that we can fix it before the final release.

CHANGES since 6.0.0

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

To see a summary of changes, please read the…

Super Good Software 

Solidus Conf 2019 In Review

Last week, the Solidus community gathered in Salt Lake City to discuss the future of the platform and ecosystem. Over the course of four days, we discussed where we’re at, where we’re headed, and laid the groundwork for moving the platform forward.

The History of Solidus Conf

Solidus Conf has existed in some form since the very beginning of the project. In the spring of 2015, developers from Stembolt and Bonobos disappeared into the forest near Whistler, BC and emerged after a week with a plan and a direction for the new platform.

Every year since there’s been another conference: 2016 we invaded Toronto, 2017 was across the pond in London, and last year we found ourselves talking Solidus…

Ruby Weekly 

This week's Ruby news

#474 — October 31st, 2019

Read on the Web

Ruby Weekly

HTTPX: A Ruby HTTP Library 'for Tomorrow' — httpx has a slew of features, the most interesting being HTTP/2 support and concurrent requests by default.

HoneyryderChuck

A Quick Speed Update on Ruby 2.7 Preview 2 — Last week we announced the release of Ruby 2.7 preview 2 (final due on Christmas Day as usual) and Ruby benchmarker extraordinaire Noah has already put it through its paces.. don’t get too excited, it’s barely faster than 2.6 so far.

Noah Gibbs

eBook: Best Practices for Optimizing Postgres Query Performance — Learn how to get a 3x…

Saeloun Blog 

Rails 6 adds guard against DNS rebinding attacks

Rails 6 has added guard against DNS rebinding attacks by allowing whitelisting of hosts in config. The guard is active by default for development environment and can be availed optionally for other environments.

What is a DNS rebinding attack?

A DNS rebinding attack occurs when the attacker uses a web page to run malicious client side script to sneak into victim’s network and use their browser as a proxy to attack devices on the same network.

How does this affect my Rails app?

The attacker can use DNS Rebinding to perform remote code execution (RCE) on the Rails application running locally. With the correct approach, the attacker can gain access to our local ENV information and all…

Semaphore 

Continuous Delivery Co-Author Uncovers the Top Obstacles for Development Teams

In this week’s episode of Semaphore Uncut, I had the honor of speaking with author, consultant, and continuous delivery thought leader Dave Farley

Dave, who has been in the industry for more than 30 years, was kind enough to share his experience as a strategic software development consultant, industry patterns (and anti-patterns) he has observed, best practices for setting up successful testing strategies, and more. 

Listen to our entire conversation below, and check out my favorite parts in the episode highlights!

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…

Ruby Inside - Medium 

Local Time deep dive

Deep dive into the code of Local Time

Time Localization is hard. How do we display the same time to users in different locations around the world with different time zones? Even more so, what time zone do we save in the database? The time in Sydney, the time in New York, or the time in Los Angeles?

Luckily, this problem was solved long ago with the convention to save a “neutral” form and accepted standard of time value: UTC . So to solve this problem we save the time in UTC and then convert it to the user’s local time zone through JavaScript. This keeps things simple and bugs-free.

In this post, we’ll see how the Local Time gem actually solves this problem as we dive deep into the code and…

Honeybadger Developer Blog 

Managing PostgreSQL partitioned tables with Ruby

We use partitioned tables in our primary PostgreSQL database to efficiently expire old data, as deleting a bunch of data from a huge table can cause database performance to suffer. Prior to version 10, PostgreSQL didn't have native support for partitioned tables, so we used the pg_partman extension to implement partitioning. It works by using PostgreSQL's table inheritance to create child tables of the table that is to be partitioned and triggers to insert data into the child tables rather than the parent table. That extension has worked well for us, but it has a downside -- it isn't an option when you are using Amazon RDS, as it isn't supported. Now that that PostgreSQL has support for…

Ruby on Rails Podcast 

293: Speed as a Feature with Gannon McGibbon

Gannon McGibbon is a Software Developer at Shopify. He primarily works on improving codebase health of Shopify's monolithic Rails app. Gannon regularly contributes to open source with commits on Rails, Ruby, and Rubocop. He joined Brittany to discuss his latest blog post, "How to Write Fast Ruby on Rails code".

Links for this episode:

JRuby.org News 

JRuby 9.2.9.0 Released

The JRuby community is pleased to announce the release of JRuby 9.2.9.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.

Ruby Standard Library

  • The Ruby Standard Library has been updated to Ruby 2.5.7. JRuby will now report this as our equivalent compatible Ruby version. (#5917)

  • RubyGems has been updated to version 2.7.10.

Security Updates

  • This release removes an exploitable version of JQuery used by the rdoc library. See…
BigBinary Blog 

Rails 6 adds ActiveStorage::Blob#open

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

Rails 6 adds ActiveStorage::Blob#open which downloads a blob to a tempfile on disk and yields the tempfile.

>> blob = ActiveStorage::Blob.first
=> <ActiveStorage::Blob id: 1, key: "6qXeoibkvohP4VJiU4ytaEkH", filename: "Screenshot 2019-08-26 at 10.24.40 AM.png", ..., created_at: "2019-08-26 09:57:30">

>> blob.open do |tempfile|
>>   puts tempfile.path  #do some processing
>> end
# Output: /var/folders/67/3n96myxs1rn5q_c47z7dthj80000gn/T/ActiveStorage-1-20190826-73742-mve41j.png

Processing a blob

Let’s take an example of a face detection application where the user images are uploaded. Let’s assume that the images…

Saeloun Blog 

Rails 6 removes Action View helper image_alt

Rails 5.2 deprecated the Action View helper image_alt(src).

The method takes the src argument, which can be an image file path. It removes the basename and the digest of the image file path, and returns a titleized string after replacing hyphens and underscores with spaces.

Let’s see an example:

2.6.5 :002 > image_alt('images/pencil-icon.png')
 => "Pencil icon"
2.6.5 :003 > image_alt('images/admin_user_icon.png')
 => "Admin user icon"
 

Usage in image_tag

Before deprecation, image_alt was used to autogenerate alt text from the src attribute of an image_tag.

Example:

Adding the following in a view:

<%= image_tag 'brand-logo.png' %>

Would render:

<image src='/images/brand-logo.png' 

Problems with…

Saeloun Blog 

Rails 6 adds after_save_commit

Rails had provided an after_commit callback for ActiveRecord objects. It is called after a record has been created, updated or destroyed.

We can also use below shortcut of after_commit when creating, updating or destroying a record respectively:

  • after_create_commit
  • after_update_commit
  • after_destroy_commit

Rails has a separate shortcut for create and update, but a comman callback for creating or updating a record was missing.

Rails 6 introduces a shortcut for after_commit :hook, on: [:create, :update]

Before Rails 6:

class User < ApplicationRecord
  after_commit :log_user_saved, on: [:create, :update]

  private

    def log_user_saved
      puts "User saved successfully."
    e…

In Rails 6:

With…

Julia Evans 

Some research on shipping print zines

I’ve been doing some preliminary research on shipping printed zines, since Your Linux Toolbox is out now and a bunch more people have been asking about print copies of my other zines. I thought I’d write down what I’ve learned so far because it turns out shipping is pretty complicated!

My original question I was trying to answer was “can I ship a single zine anywhere in the world for less than $6 or so?“, so let’s start there.

Surprisingly the best single resource I found was this very extensive PCMag article on e-commerce fulfillment services.

why not use letter mail?

The most obvious way to send a zine inexpensively in the mail is with letter mail – letters smaller than 10” x 6” and…

Getaround Engineering 

Improving Performance with Flame Graphs

Recently we had reason to investigate the performance of one of our most commonly used endpoints. We find New Relic to be a great tool for identifying and exploring performance problems, but what about when performance isn’t exactly a problem per se, but we’d like to optimize it all the same?

Often the key to understanding can be in effective visualization of the problem, so in this short post we’ll explore how to do just that using Flame Graphs.

Generating the Graph

We won’t go through this in detail, because it’s very well covered in this good blog post from 2016. We found the following development environment setup process effective:

# Gemfile
gem "ruby-prof-flamegraph"

#…
All Ruby Podcasts by Devchat.tv 

MRS 101: Taylor Jones

My Ruby Story this week welcomes Taylor Jones, Support Engineer at Heroku. Charles asks Taylor how he ended up at Heroku. Taylor shares his journey after majoring in Computer Science at Auburn University.

Taylor had a lot of downtime in his first job so he started learning Rails online. Then after he graduated he was able to get more chances working full time with Ruby. He then started speaking at conferences such as RailsConf.

Charles and Taylor talk about how working at a place you really want to is not a pie in the sky but actually is doable if you position yourself correctly. For example Taylor really wanted to work at Heroku and was friends with the people at Heroku. When there was…

JetRockets 

onChange trigger example with React

The Bike Shed 

220: Adequately Fun

On this week's episode, Chris and Steph chat about their new client projects, VimScript, and ways to automate refreshing materialized views in tests. They also play the game Overrated/Underrated, created by Tyler Owen, and respond to a CS student who is feeling overwhelmed by the various technologies and looking to transition from tutorials to meaningful projects.

This episode of The Bike Shed is sponsored by Honeybadger.

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

Saeloun Blog 

Using bind parameters in Active Record for SQL security and performance

What are bind parameters

Bind parameters are a way to pass values into the SQL statement without embedding the values into the SQL as literals. The values are provided to the SQL statement through parametrization or using a separate API call.

There are two benefits of using bind parameters:

  • Security - Preventing injection attacks by quoting
  • Performance - Improving performance using prepared statements

Security

Bind parameters are the most effective way to fix SQL injection issues. When you embed the user-supplied literals into the query, Active Record cannot perform quoting on it. But when the literals are provided as a parameter, Active Record will quote the literals to prevent…

Julia Evans 

SQLite is really easy to compile

In the last week I’ve been working on another SQL website (https://sql-steps.wizardzines.com/, a list of SQL examples). I’m running all the queries on that site with sqlite, and I wanted to use window functions in one of the examples (this one).

But I’m using the version of sqlite from Ubuntu 18.04, and that version is too old and doesn’t support window functions. So I needed to upgrade sqlite!

This turned to out be surprisingly annoying (as usual), but in a pretty interesting way! I was reminded of some things about how executables and shared libraries work and it had a very satisfying conclusion. So I wanted to write it up here.

(spoiler: the summary is that https://www.sqlite.org/ho…

RubyGuides 

How to Use Queues in Ruby

A queue is like a waiting list.

Imagine you’re waiting in line to buy the latest Apple product, getting a movie ticket, or to pay for your groceries.

These are queues!

You can use queues in your Ruby projects.

How?

Queues allow you to process things in order of arrival, so they can be helpful for anything that requires things to be given priority the longer they have been waiting for.

You can apply this to:

  • Model a real-world queue
  • Implement algorithms like Breadth-First Search (BFS)
  • Control access to a shared resource, like CPU, disks, printers, etc.

Now…

Let’s see some code!

How To Implement A Queue in Ruby

An array can behave like a Queue if you use the right methods.

These methods are:

avdi.codes 

On Gatekeeping, Complicity, and Arrival

The Ruby Rogues Years

Tell me if you’ve heard this one: four white guys ask a fifth white guy to join their podcast.

Being invited to Ruby Rogues in 2011, first as a guest and then as a panelist, was a thrilling moment for me. It was one of my first experiences of feeling like I’d “arrived”; like I’d achieved the acknowledgment and respect of my peers. It felt like a validation that I was competent and that I belonged. And over the following years it opened a lot of doors for me.

At the time, I didn’t think so much about how this is a privilege not everyone shares: the expectation that eventually, if you work hard, you’ll receive that kind of validation. How not everyone spends…

OmbuLabs Blog 

The Manual Tester: Becoming the Best QA Asset For Your Team

No app is flawless. We all know that. Quality Assurance is an important part of any software development process and the better the tester, the higher quality the software that gets deployed to production.

But… how to be a better manual tester? Applications have evolved greatly and are becoming more and more powerful, but the manual testing process stays pretty much the same. So what is it that will make you stand out?

Here at OmbuLabs we have some techniques that we employ that ensure our high satisfaction rates. In this post, we’ll share some tips with you.

Saeloun Blog 

Ruby 2.7 adds inherit as an optional argument to Module#autoload?

Module#autoload

This method registers a file path for the given class or module and lazily loads the module the first time it is accessed.

For Example:

# person.rb
module Person
  autoload(:Profile, './profile.rb')

  puts "Profile is not loaded"
  Profile
  puts "Profile has been loaded"
end

# profile.rb
module Profile
  puts "Profile is loading"
end

Now let’s run person.rb

> ruby person.rb
Profile is not loaded
Profile is loading
Profile has been loaded

Module#autoload?

This method returns the registered file path if the module is not loaded and nil if the module has already been loaded.

# person.rb
module Person
  autoload(:Profile, './profile.rb')

  p autoload?(:Profile)
  P…
Appfolio Engineering 

Ruby 2.7preview2, a Quick Speed Update

As you know, I like to check Ruby’s speed for running big Rails apps. Recently, Ruby 2.7 preview2 was released. Normally Ruby releases a new version every Christmas, so it was about time.

I’ve run Rails Ruby Bench on it to check a few things - first, is the speed significantly different? Second, any change in Ruby’s JIT?

Today’s is a pretty quick update since there haven’t been many changes.

Speed and Background

Mostly, Ruby’s speed jumps are between minor versions - 2.6 is different from 2.5 is different from 2.4, but there’s not much change between 2.4.0 and 2.4.5, for instance. I’ve done some checking of this, and it’s held pretty true over time. It's much less true of prerelease Ruby…

Riding Rails 

Permanent public URLs for storage blobs and more

Hello Ruby folks. Wojtek from this side reporting on latest additions to Rails codebase.

Add permanent URLs for public storage blobs

It is now possible to configure Active Storage to hold public/private blobs. Public services will always return a permanent URL.

Improve inversing associations

Adds support for inversing belongs_to -> has_many Active Record associations through a config option.

Support for overrides in “zeitwerk” mode inflectors

Helps to define custom autoload inflections independently from Active Support.

Support errors translation lookup on indexed attributes

When using indexed errors option, translated messages for them will be looked up by the standardized key.

A…

AkitaOnRails.com 

The Conf 2019 Edition Report

Again, I am very overdue with this report. Travel and video editing got in the way. I apologize for that. On the other hand, the recordings are all ready for you thanks to InfoQ Brasil. Check it out:

The main thing about this year's event was undoubtedly the number of attendees. We almost doubled from last year, from the 350 to almost 600 people (575 to be exact). Last year we had great talks and this year was no different. Every year it's becoming increasingly difficult for me to do the selection. I congratulate everybody that participated.

event

All speakers had important and interesting subjects, going from Data Sciences, Elixir, Architecture, Kubernetes,…

Remote Ruby 

Managed Databases in Hatchbox, Stripe Workflows, ActionText, and ActionMailbox

In this episode, we talk about Chris' adventures implementing managed database support into HatchBox, the different workflows you can take when implementing Stripe into an application, and Jason's Rails 6 project using both ActionText and ActionMailbox.
Awesome Ruby Newsletter 

💎 Issue 179 - Please Don't Write Clever Code

Ruby Weekly 

Ruby 2.7.0 Preview 2 Released

#473 — October 24, 2019

Read on the Web

Ruby Weekly

Ruby 2.7.0 Preview 2 Released — Progress towards a final Ruby 2.7 release on Christmas Day is going well! As a reminder, there are some big new bits in 2.7: ‘compaction’ GC (which defragments the memory space your programs are using), pattern matching, irb enhancements (including multi-line editing support), and quite a bit more. It’s a perfect time to get playing.

Yui Naruse

Fun with each_with_object and Other Enumerator Adventures — This really is fun and a demonstration that even if you’re an experienced Rubyist, there’s often another, cleaner way to…

RubySec 

Loofah XSS Vulnerability

RubySec 

ruby_parser-legacy world writable files allow local privilege escalation

RubySec 

brakeman world writable files allow local privilege escalation

Ruby on Rails Podcast 

292: Finesse in Quitting (Brittany Martin on the Bikeshed)

[Repost from the Bikeshed] On this week's episode, Steph Viccari is joined by Brittany. 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.

Links for this episode:

Ruby on Rails Podcast 

292: Finesse in Quitting (Brittany Martin on the Bikeshed)

[Repost from the Bikeshed] On this week's episode, Steph Viccari is joined by Brittany. 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.

Links for this episode:

Saeloun Blog 

Ruby Lazy Enumerators

Every time we use methods like map, collect, select, each we create an enumerator. Because of enumerators, methods can be chained like

[1, 2, 3].map { .... }.select { .... }

Calling each or select returns an enumerator as shown below:

[1, 2, 3].each
=> #<Enumerator: ...>

[1, 2, 3].select
=> #<Enumerator: ...>

Normal Enumerator

Let’s say, we have to fetch 10 Twitter user profiles, who have @rails in their profile bio.

Assume, we have 1000 twitter user IDs. We may follow this approach to fetch the 10 users:

# Array of twitter user id's
twitter_user_ids = [...]

twitter_user_ids.map { |user_id| TwitterClient.user(user_id) }
  .select { |data| data[:description].includes?("@rails") }
  .

We iterated over 1000 users, even if the first 10 users had @rails in their bio.

Lazy Enumerator

The above code can be improved by adding lazy as…

Test Double | Our Blog 

A Model View Controller Pattern for React

Introduction

React is an amazing library. Over the last 5 years it has transformed the landscape of frontend development and spawned an incredible ecosystem of tools, libraries, and patterns. Over that time, React has changed quite a bit. As React has evolved, so too have our applications, tools, and approaches.

This year (2019), React went through one of its biggest changes with React v16.8: The One With Hooks. Combined with the official Context API in v16.3, this update dropped a grenade into the React world. As developers like Kent C. Dodds pointed out, complex state management became something that any React developer could implement—without bringing in tools like Redux, MobX, or Apollo.

Saeloun Blog 

Rails 6 adds tools for Action Cable testing.

What is Action Cable?

Rails 5 added Action Cable, as a new framework that is used to implement Websockets in Rails. With this we can build realtime applications in Rails.

Testing Action Cable prior to Rails 6

Prior to Rails 6, there were no tools for testing Action Cable functionality provided out of the box. One can use action-cable-testing gem which provides test utils for Action Cable.

Rails 6 adds tools for Action Cable testing

In Rails 6, the action-cable-testing gem was merged into Rails, in addition to other additional utilities. so now we can test Action Cable functionalities at different levels.

Testing Action Cable

Testing connection

Consider the following example:

modu…
Ruby News 

Ruby 2.7.0-preview2 Released

We are pleased to announce the release of Ruby 2.7.0-preview2.

A preview version is released to gather feedback for the final release planned to release on December. It introduces a number of new features and performance improvements, most notably:

  • Compaction GC
  • Pattern Matching
  • REPL improvement
  • Separation of positional and keyword arguments

Compaction GC

This release introduces Compaction GC which can defragment a fragmented memory space.

Some multi-threaded Ruby programs may cause memory fragmentation, leading to high memory usage and degraded speed.

The GC.compact method is introduced for compacting the heap. This function compacts live objects in the heap so that fewer…

BigBinary Blog 

Rails 6 adds ActionMailer#email_address_with_name

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

When using ActionMailer::Base#mail, if we want to display name and email address of the user in email, we can pass a string in format "John Smith" <john@example.com> in to, from or reply_to options.

Before Rails 6, we had to join name and email address using string interpolation as mentioned in Rails 5.2 Guides and shown below.

  email_with_name = %("John Smith" <john@example.com>)
  mail(
    to: email_with_name,
    subject: 'Hey Rails 5.2!'
  )

Problem with string interpolation is it doesn’t escape unexpected special characters like quotes(“) in the name.

Here’s an example.

Rails 5.2

irb(main):001:0> %("John…
All Ruby Podcasts by Devchat.tv 

MRS 100: The Origin and Impact of My Ruby Story

My Ruby Story celebrates its 100th episode. To commemorate the 100th episode host Charles Max Wood talks about how My Ruby Story podcast started and how it progressed.

My Ruby Story started off as a spin-off of Ruby Rogues. Acting upon advice from a business coach he was working with at the time, Charles misunderstood her suggestion to double on Ruby Rogues and instead proceeded to create a podcast similar to Ruby Rogues. Over the years, the show proceeded to inspire many developers who are just starting out and the show developed a fan base of its own.

Over the years, My Ruby Story has helped people get better jobs, shaped their careers. For those who have been positively affected,…

All Ruby Podcasts by Devchat.tv 

RR 435: Alternatives to Adding React with Graham Conzett

Graham Conzett has been a developer for 12 years. He has worked with Ruby and Rails for half of that, and currently works for a company that does large format touchscreens. Graham gave a talk at RailsConf 2018 called “Old School JavaScript and Rails” where he talks about the experience of JavaScript fatigue. The world of JavaScript changes very quickly, and sometimes it feels like there’s a new framework every week. Because there is no clear winner among these frameworks, many Rails developers feel compelled to reach for something like React. However, there are many strategies for doing JavaScript in Ruby and in Rails that existed before these frameworks, so you can accomplish what you want…

The Bike Shed 

219: Seeking That Middle Option

On this week's episode, Steph catches us up on her ever-growing collection of mechanical keyboards, Chris talks about his recent purchase of an apple watch, and they follow up a previous discussion around case-sensitivity (or insensitivity) in URLs and email addresses. They round out the discussion with a chat about writing blog posts and some postgres fun, and finally discuss the merits and drawbacks of monorepos.

This episode of The Bike Shed is sponsored by Honeybadger.

If you're enjoying The Bike Shed, we'd love it if…

Julia Evans 

Your Linux Toolbox: a box set of my free zines

About a year and a half ago, No Starch Press got in touch with me about publishing a print box set of my zines. I have two kinds of zines right now:

  • 6 free zines (which are the first ones I wrote)
  • 6 zines that cost $10-$12 each (the newer ones)

This set is basically a really lovely box set of all of the free zines, plus Bite Size Linux :). Here’s what’s in the box:

I’m really happy to get these zines into print, and that I can still give away all of the zines in the box away for free on my website…

Saeloun Blog 

Rails 6 adds Active Record Relation#pick

Before Rails 6, loading only the first value from the set of records was not very straight forward.

Suppose we want to fetch the name of the the first book published by author Behrouz A. Forouzan.

Book.includes(:author).where(authors: {name: 'Behrouz A. Forouzan'}).order(:published_on).limit(1).pluck(:name).first
# SELECT "books"."name" 
# FROM "books" 
# LEFT OUTER JOIN "authors" ON "authors"."id" = "books"."author_id" 
# WHERE "authors"."name" = ? 
# ORDER BY "books"."published_on" ASC 
# LIMIT ?  [["name", "Behrouz A. Forouzan"], ["LIMIT", 1]]
 => "Data Communication and Networking"

In order to load just single column value in the above case, we need to add limit(1) and first along…

RubyGuides 

How to Use The Ruby Gets & Ruby Chomp Methods

You’re writing a Ruby program & you want to ask the user a question…

How do you go about that?

Well, you can use the Ruby gets method.

You call gets

Then your program starts waiting for you to type something with your keyboard & press the enter key.

The result?

You get back a string.

This string has the contents of what you (or the user) typed in, so if you assign this string to a variable you’ll be able to use it.

A common example is a greeting program.

It looks like this:

name = gets.chomp

puts "Hello #{name}, nice to meet you!"

The #{name} thing is called string interpolation

Give this a try & see for yourself how it works.

  • First, save this code into a “greeting.rb” file
  • Then,…
Ruby News 

2020 Fukuoka Ruby Award Competition - Entries to be judged by Matz

Dear Ruby Enthusiasts,

The Government of Fukuoka, Japan together with “Matz” Matsumoto would like to invite you to enter the following Ruby competition. If you have developed an interesting Ruby program, please be encouraged to apply.

2020 Fukuoka Ruby Award Competition - Grand Prize - 1 Million Yen!

Entry Deadline: December 11, 2019

Fukuoka Ruby Award

Matz and a group of panelists will select the winners of the Fukuoka Competition.The grand prize for the Fukuoka Competition is 1 million yen. Past grand prize winners include Rhomobile (USA) and APEC Climate Center (Korea).

http://myfukuoka.com/category/news/ruby-news/

Programs entered in the competition do not have to be written entirely in Ruby but…

Andy Croll 

Use Active Support in Rails for deprecation messages

When authors of open source libraries change major functionality they often adhere to something called semantic versioning. At its simplest you can think of it as a rule meaning features aren’t removed until a major version is released.

Before any big changes it’s a good idea to send messages to users of the software in a harmless, but visible, way. This is often done via the logs output when the code runs.

You might have seen these when your tests run or in your live application logs.

blah/blah/file.rb:34: warning: constant ::Fixnum is deprecated

Although in our private codebases our changes do not impact hundreds of other unseen developers, it’s still a good idea to communicate with…

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 

GitHub Actions with Ruby on Rails: Setting up Continuous Integration

Learn how to set up GitHub Actions to run 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…

Ruby Together News 

Growing Ruby Together

Growing Ruby Together

Recently I joined Ruby Together to help grow the membership community. Having been a Ruby developer for nearly 15 years, this represents a truly exciting opportunity to give back to the community and be a part of a meaningful organization. But the first question I had to figure out was, why grow? Ruby Together has nearly 200 members, which is a great start. Our current membership base allows us to make critical security and bug fixes to RubyGems and Bundler, as well as fund mentorship programs and grants for open source Ruby software.

The obvious answer is more members means more resources to improve Ruby projects. But the less obvious answers are also exciting and…

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…