ruby

Run single Rails test

Snippet

Run a single Rails test in a test file by including the test file (which will run all the tests) and -n with the test name prefixed by test_ and having underscores for spaces for the specific test name

# for the test titled: test 'submitting review'
rails test test/models/submission_review_test.rb -n test_submitting_review 

Alias Rails columns

Snippet

When working with APIs, sometimes the fields from the APIs are reserved keywords (looking at you, Shopify, and your type fields). When saving the data directly, you don't can't have a field in the database named type, but you don't want to manipulate the parameters and models for every query call. That would suck.

Alias the field instead.

class User < Activerecord::Base
  alias_attribute :new_column_name, :real_column_name
end
 
# specific use case (metafields at Shopify)
ActiveRecord::Schema.define(version: 2022_07_04_191939) do
  create_table "metafields", force: :cascade do |t|
    t.string "namespace"
    t.string "key"
    t.string "value"
    t.string "value_type"
    t.string "variant_type"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end
end
 
# aliased
class Metafield < ApplicationRecord
  # the Shopify object has 'type' but 'type' is a DB reserved word
  alias_attribute :type, :variant_type
end

Ruby Notes

Snippet

Yeah, those small details I need to keep looking up as I switch among ruby, javascript, php, and python on any given day.

See also:
https://www.techotopia.com/index.php/Ruby_String_Replacement,_Substitution_and_Insertion
https://www.rubyguides.com/2019/07/ruby-gsub-method/

CSV notes at https://ruby-doc.org/stdlib-2.6.3/libdoc/csv/rdoc/CSV.html

# remove only leading and trailing whitespace (like PHP's trim) 
str.strip
 
# use a regular expression ( this evaluates to 
str = "white chocolate"
str.gsub("white", "dark")
 
# which are groupings, btw (this evaluates to "1a")
"a1".gsub(/(\w)(\d)/, '\2\1')
 
# puts and print
print "use a return at the end\n"
puts "automatically adds the newline"

Use bundle to add gems to Gemfile

Snippet

Similar to npm add module --save to add a node package to the package.json file, you can use bundle to download, install and save a gem to the Gemfile.

bundle add {gem} {version}
# examples
bundle add pdf-reader "2.4"
 
bundle add pdf-reader 

Install different gems in Docker container

Snippet

I have a development environment that is used locally within docker containers, and deployed to a Heroku-like environment, which has a different setup than the local Docker setup. When running locally in Docker containers, I want to install debase and the ruby-debug-ide gems, so that I can use RubyMine locally, but these are not needed when deployed to the development instance. The deployment does not use the Docker / docker-compose files, so I'm okay with having them be local-development specific.

The trick I found was to use groups in the Gemfile.

In my Dockerfile, I'd call out the groups with the --with={groups} arguments:

RUN bundler install --with=development,docker

group :docker do
  gem 'debase'
  gem 'ruby-debug-ide'
end

What gems are installed?

Snippet

Have a Gemfile or a Gemfile.lock and want to see what versions are installed.

gem list

Ruby Get Instance Name

Snippet
# controller is whatever object you're looking at
ObjectSpace._id2ref(controller.object_id) 

Pretty print a json file

Snippet

JSON comes over the wire with minimal spaces, making human parsing of the object difficult. The json lib provides an easy way to reformat it into an indented format.

Remember to use #!/usr/bin/env so that any rbenv or rvm specific versions of ruby will be used.

Dump this into a file, say, format-json.rb, and use with:

format-json.rb my-squashed.json > nicely-readable.json

Usage:

#!/usr/bin/env ruby
 
require 'json'
 
exit if ARGV[0].nil?
 
puts JSON.pretty_generate(JSON.parse(File.read(ARGV[0])))

Dump request into a tmp file

Snippet

Dump the content of an http request into a /tmp file.

file_name = '/tmp/' + params[:type].gsub(/\./, '_') + '.' + params[:api_version] + '.json'
File.open(file_name, "w+") do |f|
  f.write(request.raw_post)
end

Minitest Cookbook

Book Notes

Okay, so, for the record with this review, The Minitest Cookbook was not the book I needed, nor expected. Take the rest of this review with a grain of salt as a result of that disclaimer.

I've been writing code that is tested with minitest tests for nearly a year now. I find that my understanding of when to use mocks versus stubs versus expects versus pick something else, to be somewhat lacking. Sure, I can cut and paste another test and modify as I need to modify it to fit my particular test case, but I don't want to copy and modify a test. I want to understand the reasoning behind what I'm doing and create a test, to understand "this is what I'm testing and this is how I go about it." Being able to do that quickly requires that I understand the system that I'm working on as a whole perhaps better than I do, but being able to do it without a full understanding is needed at this point.

So, I picked up this book as the recommended minitest book. Lots of favorable reviews, this is the book you want if you're learning minitest.

Except, it isn't.

It's too complicated for beginners (are n00b or newbies still derogatory terms, or have they been embraced by beginners - I guess if beginners are okay with being called dummies, they're okay with being n00bs), and not well organized for an intermediate user. I'd consider myself halfway between those two designations, so figured I'd get it, but, eh, didn't really work out that way.

Pages