ActiveRecord to JSON API Part 6: Mimicking AR


This post is by Hashrocket from Hashrocket


Click here to view on the original site: Original Post




As we worked through the conversion from ActiveRecord to JsonApiClient, we came across some methods implemented by ActiveRecord that would still be useful to have around.

Background

We were building an internal JSON API using the following libraries:

For more information on our goals and set up for the internal API, see part 1 of this series.

Pluck

One of the first things we noticed we were converting over and over again was ActiveRecord’s pluck method. With the JsonApiClient resources, we were converting all the ActiveRecord pluck calls to chaining select(:field).map(&:field).

Not only was this repetitive and time consuming to convert, but we felt like it was burdensome for future developers on the application to have to remember to do.

We decided to try to figure out how we could implement pluck on the Continue reading “ActiveRecord to JSON API Part 6: Mimicking AR”

The nature of software and fixed bid contracts


This post is by Hashrocket from Hashrocket


Click here to view on the original site: Original Post




Software is abstract. It is soft, where is it? I can not hold it in my hands or feel it's weight. Is it substantial, insubstantial? Are you impressed by the effort I put into it? Are you disappointed in my apparent slowness while making this software?

Before I write software for you, I am confident that it will be wholly unique. Never before will it have been written, or else why would you want it? If it's not unique, can you instead purchase it elsewhere? Even if it exists, you can't purchase it, and you'd like me to recreate it, I cannot duplicate someone else's software bit for bit. That's like trying to act Patrick Stewart's MacBeth in a way that's indistinguishable from Patrick Stewart. With my first breath I will have failed. I have not lived Patrick Stewart's life, my voice box and diaphragm are different dimensions, and my Continue reading “The nature of software and fixed bid contracts”

ActiveRecord to JSON API Part 5: Polymorphism


This post is by Hashrocket from Hashrocket


Click here to view on the original site: Original Post




The Rails application we were working with had a number of polymorphic relationships that included the models we were moving to the JSON API, as well as a polymorphic relationship within the models being migrated.

This raised an interesting question for us. How do we maintain those relationships without changing the core functionality of the app and the models involved? And how will the polymorphic API associations function?

We wound up facing two issues with polymorphism during the conversion process.

  1. Making the ActiveRecord resources remaining in the application capable of being related to both other ActiveRecord resources, and to JsonApiClient resources
  2. Making JsonApiClient resources fetch polymorphic API associations when the associated data was not eager loaded from the API.

Background

We were building an internal JSON API using the following libraries:

For more information on Continue reading “ActiveRecord to JSON API Part 5: Polymorphism”

Cast/Share your iPhone/iPad screen to Mac


This post is by Hashrocket from Hashrocket


Click here to view on the original site: Original Post




If you are pairing remotely on a mobile web project or doing a presentation that includes a mobile demo it is often helpful to share your iOS screen on your Mac.

Recently, we have been working on a project that uses ApplePay on the web which proved difficult to test on a desktop computer, and we wanted to show how it worked on an iPhone.

There are quite a few software products that can help you achieve this goal, but many of them cost money or are unreliable. In this post I will share with you some solutions I have used successfully to share my mobile device's screen. I’m not going to cover all the solutions that exist out there, and ultimately there are no right or wrong answers – it is whatever works for your use case.

Reflector – Cost: $14.99

Reflector is a software solution by Air

Imgur
Imgur
Imgur
Imgur
Imgur
Imgur
Imgur

Continue reading “Cast/Share your iPhone/iPad screen to Mac”

ActiveRecord to JSON API Part 4: Custom Sorting


This post is by Hashrocket from Hashrocket


Click here to view on the original site: Original Post




The JSONAPI::Resources automatically supported sorting on database fields, but didn’t handle custom sorting without requiring overrides to library methods.

Background

We were building an internal JSON API using the following libraries:

For more information on our goals and set up for the internal API, see part 1 of this series.

Custom Sorts

In a few of the ActiveRecord models we were converting, there were some custom sort methods that we needed to be able to specify through the API.

class LocalAPI::Foo < ApplicationRecord
  # …

  def self.abcs_last
    order("CASE foos.some_field WHEN 'abc' THEN 1 ELSE 0")
  end

  # … 
end

The JSONAPI::Resources automatically supported sorting on database fields, but in their documentation, they specify that any custom sorts require overriding the apply_sort method on the specific JSONAPI::Resource you’re working Continue reading “ActiveRecord to JSON API Part 4: Custom Sorting”

Pick a Good Name


This post is by Hashrocket from Hashrocket


Click here to view on the original site: Original Post




I've been fortunate to work on some long-running projects, and they always confirm the importance of choosing good names. In this post, I'd like to talk about my thoughts on what makes a name good.

There are only two hard things in Computer Science: cache invalidation and naming things.
— Phil Karlton

The importance of naming things seems abstract until you've done it badly a
lot. Imagine a function like this:

def a(b, c)
  d = b + c
  d
end

This is often called 'golf code' because it requires few keystrokes to
type, relative to something more verbose. It's impossible to maintain.
Only the person who wrote the function knows what a, b, c, or d
represent. Everybody else has to load the domain into their head every time
they see it.

Bad names make it difficult to search through the code. Continue reading “Pick a Good Name”

ActiveRecord to JSON API Part 3: Handling Filtering


This post is by Hashrocket from Hashrocket


Click here to view on the original site: Original Post




Did you know that Puma has a 10,240 character query string limit? We do now.

In the process of building our internal JSON API, we found two issues with handling filtering:

  1. Query string limitations
  2. Querying for an array of IDs when some values were nil

Background

We were building an internal JSON API using the following libraries:

For more information on our goals and set up for the internal API, see part 1 of this series.

Query Strings

Given that the JsonApiClient filtering methods use an HTTP GET with query string parameters, character limits quickly became a concern for us. How could we ensure that some of our lengthier queries weren’t exceeding the limit and failing?

The simplest solution to us was to make the filters a POST request, even if that was a divergence Continue reading “ActiveRecord to JSON API Part 3: Handling Filtering”

Write A Reduce Function From Scratch


This post is by Hashrocket from Hashrocket


Click here to view on the original site: Original Post




JavaScript's Array object has a built-in reduce method. This is a handy,
yet underutilized method. Let's take a closer look at what reduce does and
see if we can implement it from scratch.

Reduce?

Here is what
MDN
has to say about reduce:

The reduce() method executes a reducer function (that you provide) on each
member of the array resulting in a single output value.

So, we can take an array of things and turn it into something else using a
function that we get to define.

const sum = list => list.reduce((total, val) => total + val, 0);

sum([1,2,3,4]) // => 10

The reduce method can seem pretty limiting at first when we read that it
produces "a single output value." That makes it sound like all it is good
for Continue reading “Write A Reduce Function From Scratch”

ActiveRecord to JSON API Part 2: Solving Pagination


This post is by Hashrocket from Hashrocket


Click here to view on the original site: Original Post




While building an internal JSON API for a Rails application, we came across a few issues with pagination.

  • Making Kaminari work
  • Resolving problems with pagination link parameters
  • Enabling pagination while still allowing users to get everything

Background

We were building an internal JSON API using the following libraries:

For more information on our goals and set up for the internal API, see part 1 of this series.

Kaminari

The application we were working on was using Kaminari for pagination, and one of the first things we noticed during our switch from ActiveRecord to JsonApiClient::Resources was that pagination no longer worked, but only when the page number param was not present.

Upon investigating the source code for JsonApiClient, we noticed that when the page number param was blank during pagination, the page was resolved to 0, Continue reading “ActiveRecord to JSON API Part 2: Solving Pagination”

Use Yarn Like a Pro


This post is by Hashrocket from Hashrocket


Click here to view on the original site: Original Post




Yarn is a fast, reliable, and secure alternative to NPM. In this post, we'll look at techniques to use Yarn to its fullest.

The expectations of life depend upon diligence; the mechanic that would
perfect his work must first sharpen his tools. —Confucius

Yarn is a great tool. I'm won't wade into the Yarn vs. NPM debate,
because the tradeoffs are always in flux. I just say that I've been
using it for two years on a variety of projects, and have nothing but praise.

Part of that journey has been learning Yarn's nuances, and today I'm happy to be
sharing them with you. Some of these epiphanies came to me through my own work,
and some via our company knowledge base, Today I
Learned
.

I'm going to skip the setup and some common Yarn commands; head over to Yarn's
official site
to boot up. All of these commands were
Continue reading “Use Yarn Like a Pro”

5 JavaScript Object Destructuring Tricks


This post is by Josh Branchaud from Hashrocket Articles


Click here to view on the original site: Original Post




The ES6 destructuring syntax is quite flexible. It allows us to do a lot of
nice things with objects and arrays that in the past would have taken many
distracting lines of code.

Let's look at five handy destructuring tricks for objects.

Trick #1

Remove an item from an object

// const data = { a: 1, b: 2, thingToRemove: "bye" };

const { thingToRemove, ...rest } = data;

console.log(rest); // { a: 1, b: 2 }

This is a concise way of getting a new copy of an object with a specific
key/value pair removed. Note that it is immutable and you are free to
specify as many keys as you'd like separated from the ...rest object.

Trick #2

Rename things in a destructuring

// const data = { coordinates: { x: 5, y: 6 }};

const { x: xCoord, y
Continue reading "5 JavaScript Object Destructuring Tricks"

Today I Learned 2018: Year In Review


This post is by Suzanne Erin from Hashrocket Articles


Click here to view on the original site: Original Post




Today I Learned is an open-source Elixir Phoenix project by Hashrocket. One of the fun things about January is being inspired to look back at the past year. This blog revisits some of the top trends and posts in Today I Learned of 2018.

In 2018, we at Hashrocket posted 379 TILs. On average, we collectively were learning something new every day!

Our top-two most popular posts of the year were both #elixir posts:

The three topics that we posted TILs about most often were:

  1. #javascript (56 posts)
  2. #react (52 posts)
  3. #reasonml (44 posts)

A huge portion of our work this year involved React and JavaScript so it is no surprise that we were learning a lot in those areas! Here are the top posts from each of those categories:

Managing React Router Pathnames


This post is by Josh Branchaud from Hashrocket Articles


Click here to view on the original site: Original Post




So, you've introduced
react-router into your
single page React app as a way of managing routing. The app has started to
grow. There are many top-level routes for rendering different "pages". Some
of those "pages" now have sub-routing within them for managing wizard
workflows and sections with multiple "sub-pages". This is great. The dream
of routing within your React SPA has been realized.

Fast-forward a few months, and your elegant routing solution has become a brittle, error-prone maintenance nightmare. What happened?

A Simplified Example

Early into the development of a large React SPA, I noticed the above
scenario beginning to emerge. Some of what I noticed can be summarized in
the following series of code snippets. Note: these code snippets are not
full, working examples. Only the instructive parts have been included.

/* App.js */
return (
  <Switch>
    <Route path="/" component={Home
Continue reading "Managing React Router Pathnames"

Adventures in Mentorship


This post is by Jake Worth from Hashrocket Articles


Click here to view on the original site: Original Post




This fall, I participated in the formal mentorship program at the Code Platoon
bootcamp here in Chicago. In this post, I'd like to talk about my experience as a
mentor.

For the past few years, myself and a few Hashrocket colleagues have taught a
workshop at Code Platoon, focusing on test driven development, Ruby, and
PostgreSQL. As a veteran, it's one of my favorite days of the year, and I'm
grateful Hashrocket supports this outreach.

When Code Platoon put out a call for mentors this Summer to
work with the upcoming cohort, 'Golf Platoon', I decided to give it a try.

Why Mentor?

My drive to mentor comes from the fact that I have been mentored myself by many
great people. These advisors helped me find opportunities and direct my
professional growth. From the beginning, I hoped someday to be able to provide that same service to others.

I

Continue reading “Adventures in Mentorship”

Avoiding Code Catastrophes


This post is by Jake Worth from Hashrocket Articles


Click here to view on the original site: Original Post




"Am I going to make a huge mistake in my first dev job (e.g., delete the production database) and get fired?"

I've been asked this question a few times. It's a concern that new programmers have: that they'll end up in a situation where they make the wrong call in the heat of the moment, harming their company and ending their fledgling career. Cutting the red wire fixes the production bug; cutting the green wire sets our servers on fire, or vice versa. Which one will you cut, junior developer?

I think this is a valid fear when you're new, and it's something that once crossed my mind, as a self-taught beginner. Is it possible for me to make such a gigantic mistake in my first programming job? I think the answer is no.

When you start working as a developer you will have differing levels of

Continue reading “Avoiding Code Catastrophes”

Exploring the Default Postgres Template Databases


This post is by Mary Lee from Hashrocket Articles


Click here to view on the original site: Original Post




I was recently poking around the psql terminal, and noticed something that I had never had to deal with before: the Postgres template databases. I decided to seize the moment and launched myself into an exploration of what the template databases are meant to do, and why the heck there are two of them.

My first plan of attack was to just list them and see if I could find a difference right away, but everything looked exactly the same.

postgres=# \l
                                   List of databases
   Name   |   Owner  | Encoding |   Collate   |    Ctype    |   Access privileges
----------+----------+----------+-------------+-------------+-----------------------
postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres + postgres=CTc/postgres
template1 | postgres | UTF8     | en_US.UTF
Continue reading "Exploring the Default Postgres Template Databases"

Where Am I: URL Assertions with Cypress


This post is by Josh Branchaud from Hashrocket Articles


Click here to view on the original site: Original Post




The URL that appears in the browser's URL bar is one of the first and
primary ways that users interact with our web apps. The URL tells the app
and the user of their location within the route hierarchy of the app. It
sometimes even contains state. The URL consequently serves as an excellent
first assertion when writing integration tests.

When writing Cypress integration tests, there are
several ways for us to assert about the current URL.

The cy.url() and
cy.location()
functions are the primary ways for us to gain access to information about
the current state of the URL. From there, we can perform a variety of
assertions.

We can assert about the entire URL:

// URL: http://localhost:8000/pokemon
cy.url().should('eq', 'http://localhost:8000/pokemon');
// ✅ passes

This is certain the most precise assertion. The tradeoff is that it requires
us to know something

Continue reading “Where Am I: URL Assertions with Cypress”

Wrap Parameters Without Changing Markup


This post is by Matt Polito from Hashrocket Articles


Click here to view on the original site: Original Post




While updating logic that caused a POST with a JSON body to change into a POST as multipart/form-data, I ran into an issue where the Rails controller was expected params in a nested way. Sure, I could change my inputs to have a different name that would cause the nested structure, but that was changing logic down the line.

Rails was wrapping the incoming parameters automatically since the prior request was of 'Content-Type': 'application/json'. Well, I'd really like this same behavior on my new request as it would solve my current conundrum.

Turns out ActionController has a method that can help out with that… the aptly named wrap_parameters method.

In my case, the name I needed was the same as the controller so I could use this:

class FooController < ApplicationController
  wrap_parameters format: %i[mutlipart_form json]
end

This produces a params payload like so:

ActionController::Parameters {
  "account_id_eq"=>
Continue reading "Wrap Parameters Without Changing Markup"

Query for NULL ‘or’ empty string in ActiveRecord


This post is by Matt Polito from Hashrocket Articles


Click here to view on the original site: Original Post




Sometimes you come across a query that looks for an attribute that is NULL 'OR' an empty string. Sure there are options we could employ that may remove the necessity of checking for both but let's see how we can improve our code a bit first!

The majority of the time I see this as a SQL fragment in ActiveRecord:

Foo.where("name is null or name = ''")

Which produces the following SQL:

SELECT * FROM "foos" WHERE (name is null or name = '')

Sure you can say now that ActiveRecord has or it could be done like so:

Foo.where(name: nil).or(name: '')

However, I'm currently in a project that doesn't support or yet so I went playing to see what I could come up with that wouldn't be a SQL fragment. My first thought was to

Continue reading “Query for NULL ‘or’ empty string in ActiveRecord”

Journey to ElixirDaze 2018


This post is by Jake Worth from Hashrocket Articles


Click here to view on the original site: Original Post




Last October I discovered an interesting Github issue, Elixir-Lang #6643. It was opened José Valim, the creator of Elixir.

Here's part of the introduction to this issue:

Elixir master now includes a code formatter that automatically formats your code according to a consistent style.

We want to convert Elixir's codebase to use the formatter on all files. We understand this means a lot of code churn now but, on the positive side, it means we can automatically enforce and/or format future contributions, making it easier for everyone to contribute to Elixir.1

This issue set off a massive refactoring project to get Elixir conforming with its new formatter. Today, new pull requests to Elixir must pass through the formatter without requiring changes. I think this will have a ripple effect on every Elixir project in production.

While closing this issue, José provided the following statistics on the refactor: