Archive

Coding Bits

Sometimes you just need long strings.

In tests, I sometimes like to include tiny CSVs as a part of the test code instead of a fixture file. However, that looks real gross real fast with all the linebreaks.

Heredocs to the rescue!

In Ruby, instead of:

sample_csv = "foo,bar,baz\na,b,c\nd,e,f\n,g,h,i"

You can do something like:

sample_csv = <<~EOS
   foo,bar,baz
   a,b,c
   d,e,f
   g,h,i
EOS

Isn't that much better?

Suppose you want an endpoint that returns a file that the browser would open a “file download” dialogue. You can do so by setting the Content-Disposition.

Example:

class FooController < ApplicationController
  def show
    response.headers["Content-Disposition"] = "attachment; filename=foo.txt"
    render plain: "foobar"
  end
end

In the example, when hitting the show path, most browsers will pop open a download box asking to save "foo.txt". Note, that you need to pass in "Content-Disposition" (string) and not :content_disposition (symbol).

I recently used Zappa and it’s magical!

Zappa is a tool that makes it easy to deploy Python apps to AWS Lambda. It works with Flask, Django, etc (anything WSGI-compatible) and it’s very straightforward to configure.

As someone who doesn’t enjoy a lot of ops work, Zappa opens up AWS Lambda as a possible infrastructure I can easily leverage for personal projects. Lambda can cost a lot less than EC2 instances and pushes a lot of the scaling issues to Amazon to handle.

Lambda’s not right for every project but I’m excited by the possibilities.

Pipenv is so snazzy.

Here’s a list of problems it solves: https://realpython.com/pipenv-guide/

My favorite (minor) feature is that I now no longer have to .gitignore all the virtualenv directories for Python projects.

Thoughtbot has a great guide on getting started: https://robots.thoughtbot.com/how-to-manage-your-python-projects-with-pipenv

Recently, there was a “TypeError: ‘module’ object is not callable” bug (with a workaround) but looks like it’s been fixed: https://github.com/pypa/pipenv/issues/2871

This post is a gift to my future self for when I no longer writer Python daily and need a refresher.

Chris Yeh has a wonderful post on the correct syntax to write import statements in Python.

The essence is, if you have a directory structure like:

awesome_project/
    run.py
    foo/
        __init__.py
        bar.py
        baz.py

In run.py:

from foo import bar

bar.Bar()

In baz.py:

from .bar import Bar

Bar()