While updating logic that caused a
POST with a
JSON body to change into a
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.
ActionController has a method that can help out with that… the aptly named
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]
This produces a params payload like so:
"account_id_eq"=> Continue reading "Wrap Parameters Without Changing Markup"
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”
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:
Have you had a conversation about Redux recently that has left you wondering — despite all of its praise and the assured recommendations — if you made a big mistake when you typed the words,
yarn add redux?
Jani is being a bit facetious here. But if you’ve been following along on twitter, there has been a lot of discussion about redux. The crux of the conversation is aimed at whether most apps even call for the use of redux and consequently if we, as developers, are using it when we don’t need it.
When investing in cryptocurrency, security is a huge concern. In 2014, a famous online bitcoin exchange, Mt.Gox, was the target of a hack that saw 850,000 bitcoins stolen. For many investors, this was a wake-up call. Keeping your money in an online exchange is not a smart move. The best way to protect your investment is to be proactive. There are already many strategies for storing cryptocurrency, and one of the most secure ways is cold storage. Cold storage involves generating and storing your coins private keys offline. While it might not be ideal for you to keep all of your cryptocurrency stored offline, this option ultimately provides the best security.
Like many others, I too had kept my investments on online exchanges (mainly for convenience). After a few months of investing and seeing some positive gains, I decided it was finally time to move my assets off of
Continue reading “Creating A Paper Wallet for Your CryptoCurrency with MyEtherWallet”
A view is a stored query the results of which can be treated like a table. Note that it is the query that is saved and not the results of the query. Each time you use a view, its associated query is executed.
A related concept is that of the common table expression or CTE. A CTE can be thought of as a short-lived view; you can only use it within the query in which it appears (you can refer to it multiple times, however).
Let's say that you're the SQL-savvy owner of a store that sells kits for building robots. On your site, customers are guided through the process of selecting all of the components needed to build a quadrupedal robot, i.e. getting the right motors, microcontrollers, sensors, batteries, grippers, etc.
Robots have lots of component parts and you have to make sure that the correct components for
Continue reading “Fun with Views and CTEs”
Binary search might be the most well-known search algorithm out there. If you went to school for computer science, you've probably heard the fundamentals of binary search hundreds of times. Chances are, you've been asked about binary search while interviewing for a development job – and for good reason. Binary search is a powerful algorithm. Compared to a linear search it performs very well, and the performance benefit is especially noticeable as the data set grows. A few weeks ago, I got the chance to use it in a live application, but it's been a while since I've worked with this algorithm, so I had to brush up on the implementation.
My pair and I were working on a class in one of our client's applications. This class used a lot of
finds and other linear search-esque code to check for items in sorted collections. Being the
Continue reading “Binary Searching and Ruby’s bsearch Method”
Like a diary, but for code
On a few occasions, I've started work on a brownfield project and found that, either due to poor programming practices or because there was no elegant way to implement a feature, it's been necessary to create documentation beyond what is normally included in a README. This documentation often took the form of glossaries, diagrams, or additional exposition on the codebase.
Your typical README contains all or some of the following: a short introductory paragraph, a list of dependencies, instructions on how to install the app, configuration, how to run the test suite, database creation and migration, services, and how to deploy the app. If it's an open source project, there will likely be sections devoted to listing authors, rules around contributing, the license under which it can be used, as well as additional documentation around how to use the package.
There are contexts in
Continue reading “Document Your Confusion”
Elixir 1.6 will be shipping with an important new feature: autoformatting. Let's explore it today.
Autoformatting is a common practice in languages communities like Go.
Now, this practice is coming to Elixir as part of the language. Borrowing the
arguments in favor of autoformatting
from the Go community, autoformatted code ought to be:
- Easier to write: never worry about minor formatting concerns while hacking away.
- Easier to read: when all code looks the same you need not mentally convert others' formatting style into something you can understand.
- Easier to maintain: mechanical changes to the source don't cause unrelated changes to the file's formatting; diffs show only the real changes.
- Uncontroversial: never have a debate about spacing or brace position ever again!
Whether you agree with all these points or not, the Elixir language (which is
largely written in Elixir) just underwent a massive community-powered
refactor to conform with its
Continue reading “Format Your Elixir Code Now”
PostgreSQL has shipped with the
generate_series() function for quite some
time. This function is often used to generate series of
numeric data. For
instance, in my post, Understanding Common Table Expressions with
I used it to generate a series of integers from 1 to 100.
As of PostgreSQL 8.4, support for generating series of timestamp data was
added. I don't see this used often, so let's take a look at it.
We could take a peak at the online documentation to see the function
signature, or we could pull it up in
> \df generate_series()
List of functions
Schema | Name | Result data type | Argument data types | Type
pg_catalog | generate_series | SETOF bigint | bigint, bigint | normal
pg_catalog | generate_series | SETOF bigint | bigint, bigint, bigint | normal
pg_catalog | generate_series | Continue reading "Generate Dates in PostgreSQL"
Hashrocket is known as a Vim shop; what does that mean?
When visitors learn Hashrocket is a "100% Vim shop", questions follow:
- Does everyone use Vim?
- Is Vim mandatory at Hashrocket?
- Why Vim?
These are fair, and I admit that from the outside, our company's
preference for Vim might seem unusual.
When we evangelize Vim to the development
world, via the Vim Chicago Meetup and
others, the questions become more acute. In a recent
talk I tried to sell Vim to
React.js developers. I feel obligated to have compelling, succinct
answers on hand.
I'll tackle this subject in three parts: why Hashrocket uses Vim, what
Vim is, and why we think every developer should try Vim. Few subjects
are as contentious in the development world as text editors. Whatever you use,
learn and make it your own. I hope to simply add Vim to the list of things
Continue reading “Why Vim?”
In the first part of this post we looked at a technique for swapping two
column values for existing records in a single statement. It is a relatively
sound solution that takes advantage of subqueries and a case statement.
Unfortunately, it has a couple drawbacks which we will address in this post.
This post builds off of Part 1. If you haven't already, give it a
The first drawback can be demonstrated by building on our existing example,
pages table which has the following data.
select * from pages order by ordering;
id | name | ordering
3 | Green | 1
1 | Red | 2
4 | Yellow | 3
2 | Blue | 4
In the interest of maintaining data integrity, it is reasonable to expect
that a table like this would have a uniqueness constraint on
Let's add that to ensure
Continue reading “Swap Two Column Values in SQL: Part 2”
Hashrocket's collaboration with Code Platoon continues this October!
For the past three cohorts, Hashrocket has taught an intensive all-day workshop at the Code Platoon bootcamp. Here's a
description of this unique developer training program, from their website:
Code Platoon is a Chicago-based non-profit program exclusively for veterans.
We’ll teach you full-stack development over the course of 20-weeks (6 weeks
remotely, 14 weeks in our Chicago classroom), and train you to be eligible
for paid internships and full-time employment as a web developer. No previous
programming experience is necessary.
In this post, I'd like to talk about this important program, and what we offer to it.
About Code Platoon
The world needs more
programmers; there's a mountain of work to be done. Code bootcamps rise
to this challenge by recognizing that a college degree isn't enough, or perhaps
even required, to do what we do, and that the fundamentals can be
Continue reading “Hashrocket and Code Platoon”
I recently needed to write a PostgreSQL snippet that would massage some
data. More specifically, I needed to swap the
ordering of two different
records in the
pages table. These records are made up of an
name, and an
Here is a snapshot of the data in
select * from pages order by ordering;
id | name | ordering
3 | Green | 1
1 | Red | 2
4 | Yellow | 3
2 | Blue | 4
We've been informed that we need to swap the ordering of
We can see here in this snapshot of the data that
Red has an ordering of
Blue has an ordering of
Doing a swap based on the data that we have locally would be most easily
accomplished with a couple update statements.
update pages set ordering Continue reading "Swap Two Column Values in SQL: Part 1"
How do we test a system that seems untestable?
Untested legacy code is the bane of many a developer's existence. In a
permissive language like Ruby, continued development in an untested legacy
codebase requires adding tests. Users expect certain behavior to survive each release intact.
For some systems, the traditional pyramid of test types (unit, API, and
integration) is insufficient. Unit and API tests must presumably cover hundreds
or thousands of functions; which matter? Integration tests could cover a wide
range of user interactions; which are likely? Familiarity with the project is a luxury we don't all enjoy.
I recently worked on an application that took a complex input (a
production database), ran it through a large SQL function, outputting a
giant CSV file representing thousands of permutations of data. Each stage of
the transformation was complex enough that visual inspection would fail to
determine if something was amiss.
Continue reading “Observing Change: A Gold Master Test in Practice”
For those of us that write database-backed Rails apps,
ActiveRecord is a
familiar beast. We know its various query building methods well:
limit, and even
group. The most important SQL clause is
conspicuously missing from our repertoire: the
Chances are you can't think of many, if any, times that you've used
from method. This is to be expected. The
from clause in
SQL specifies the target table of a query. In the context of ActiveRecord, the
target table is explicitly expressed by the model from which you query.
Consider the times you use one-liners such as
Developer.count. With each of these, the
table as the target of the query is expressed by the use of the
So, where does the
from method come into the picture?
Continue reading "Advanced Queries with ActiveRecord’s From Method"
The Phoenix port of Today I Learned, Tilex, is live.
Today I Learned began as a Ruby on Rails application.
We open-sourced the code after launch and have maintained it for over two
years. Our mission:
Today I Learned is an open-source project by Hashrocket that exists to
catalogue the sharing & accumulation of knowledge as it happens day-to-day.
Posts have a 200-word limit, and posting is open to any Rocketeer as well as
selected friends of Hashrocket. We hope you enjoy learning along with us.
Today, we are moving forward with an Elixir/Phoenix port of the project.
Here's a little more about the project, focusing on the work, technology, some
observations, the people behind it, and the future.
This project began over two years ago as my
Hashrocket apprentice project. Here's the launch
announcement from that time.
We open-sourced the Ruby on Rails
application in February 2016.
Continue reading “Today I Learned in Phoenix”
I remember the first time I tried out React.js. It was several years back. The promise of painlessly building interactive UIs was too enticing to ignore. As I worked through the first couple introductory tutorials, my computer screen began to shimmer in a way that it had never done before. The pure functions and composable components brought the browser to life.
Just as my excitement for React was mounting, I was stopped in my tracks. Before I could go much further I was faced with tons of tangential decisions about how the project would be configured.
Can't someone just make these decisions for me?
This is the impetus for
Create React apps with no build configuration.
This tagline is another way of saying, "Create React apps! We made all the build configuration decisions for you."
So, what kinds of things do we get for free with
redux-form library bills itself as the best way to manage your form state in Redux. It provides a higher-order form component and a collection of container components for dealing with forms in a React and Redux powered application. Most importantly, it makes it easy to get a form up and running with state management and validations baked in.
To get a feel for what
redux-form can do for us, let's build a simple Sign In form. You can follow along below or check out the resulting source code directly.
Start with React
We are going to start by getting the React portion of this application setup. The easiest way to spin up a React app is with
create-react-app. Install it with
yarn if you don't already have it globally available.
$ yarn global add create-react-app
Let's generate our project.
$ create-react-app redux-form-sign-in
create-react-app binary that is
Continue reading “Get Started with redux-form”
quickly evolving frameworks and tooling, it can be cognitively challenging
to grapple even with a familiar codebase. Even just having one less thing to
think about goes a long way in helping us deal with the rest. Figuring out
how to format each line of code is accidental complexity and one less thing
we ought to think about.
As Brian Dunn put it, "Once you stop formatting your code, life becomes
beautiful." And so does your code, but without any of the effort.
This is where Prettier comes in.
At Hashrocket, Vim is an essential part of our development tooling.
neoformat makes it easy to
prettier into our existing workflow. As you can see in the
above gif, Prettier formats the file on save.
Here is how we set it up.