When Upgrading a Rails Application with a new Ruby Version Update Both of These

Today I struggled for a little bit while upgrading the Ruby version of my Rails 6.0 application.

First, I updated the Gemfile and solved a few errors which were caused by that. Unfortunately, I forgot to document these.

The final problem I was having was an inconvience. I change had to change my ruby version in my terminal each time I opened a new terminal tab like this:

rvm use 2.6.5

Setting this each time I changed directory was annoying. The way to ensure it’s set automatically was to change the Ruby version in the .env file.

If you can’t find it via terminal, type

ls -a

in the terminal when you have changed directory into your rails app.

Otherwise, you can find it in the file structure.

how to automatically set what ruby version your rails app uses

Have fun programming!

Deeply Understanding Active Record Associations the Ruby on Rails Way

The purpose of this blog post is to describe Ruby on Rails associations deeply.

Setting up the Practice Environment

First off, I’ll create a new application for practice. I do this on the desktop as it’s an easy place to work from:

rails new association_practice

Next step is to change directories so I’m on the root level of the new application.

cd association_practice

Next, I’ll create an association to practice with. I’m going to start with planet Earth. With Earth as a starting example, I can make associations with most Earthly things.

rails g model Planet name:string

This will generate files for the migration, model, tests and fixtures. I added two planets to the fixture file and a simple test. Which you can see in the following screenshot:

Now that we have the Planet object in our system, I’m going to add the next level of association, the Continent:

rails generate model Continent name:string

This command orders the Rails app to generate four more files. I’ve added to them a little and you can see the changes in the following screenshot:

Ruby on Rails Associations

The goal of this section will be to clearly explain how to use associations to organize your web application’s data.  The association documentation on the Ruby on Rails guides is a good start, but my descriptions below I hope will help deepen your understanding of associations and how to use them.

Understanding belongs_to and has_many Associations

Continents and Planets

Let us create our first association between the continents and the planets. Each continent can belong to a single planet, but a planet can have many continents. Here’s how we assemble it:

Next we migrate the database.

rails db:migrate

Next we load the fixture data.

rails db:fixtures:load

Awesome. Now we have our fixture data loaded and our associations should be set. Here is a screen shot of the actions we can now take in the rails console.

rails c

  1. Here we search the database for a planet with the name Earth. That gives us an array with the matching result in it. We use the .first method to pull the first object. We assign this object to the variable name earth.
  2. Here we use our earth variable to get the name string data which contains the name of the planet (“Earth”).
  3. Here we list the continents associated with earth.
  4. Here we set antarctica variable to equal the continent object of our first continent, Antarctica.
  5. Here we ask the database, “What planet is associated with Antarctica?” It returns us the earth planet object. Notice that the Planet earth object has the same id at the bottom as the Earth at the top.

Work in Progress

I’m thinking of better ways to describe associations. I plan to deep my understanding of the following associations in the future:

  • has_one Association
  • has_many :through Association
    • I’m thinking of describing this by using International Organizations
  • has_one :through Association
  • has_and_belongs_to_many Association
    • I’m thinking of describing this by using members of NATO
  • Choosing Between belongs_to and has_one
  • Choosing Between has_many :through and has_and_belongs_to_many
  • Polymorphic Associations
  • Self Joins

Tribute Page to Jimi Hendrix – Responsive Web Design Project

In this tutorial, I work through creating a tribute page as part of the responsive web design project requirements for Free Code Camp. I completed this project a long time ago, but this time it’s different. This time, I record my process for writing the page and pushing it to production.

I think this is a good tutorial for combining the things we learned in the responsive web design certification curriculum. That covers basic CSS and HTML. This is a beginner project, but it provides the path to go from writing your first HTML code to pushing it to the internet.

A little more….

How to get the Last 15th of the Month Using Ruby

How do we compare date times from now against the 15th of last month?

how to make conditional statements since the 15th of last month

I’m  writing a program which assigns episodes to invoices based on the time the episodes were created. Each episode’s publishing date is recorded as follows:

pry(main)> most_recent_episode_publishing_date = Episode.last.updated_at
Episode Load (0.6ms) SELECT "episodes".* FROM "episodes" ORDER BY "episodes"."id" DESC LIMIT $1 [["LIMIT", 1]]
=> Mon, 26 May 2014 18:23:36 UTC +00:00

The above code tells us that the last episode was published on May 26th, 2014.

We save that date object which we can compare against the 15th of the previous month. First we need to get a date object for the day of the 15th of the previous month. Here’s how we do that:

pry(main)> now = Time.now
=> 2019-10-28 13:05:17 -0700
pry(main)> the_15th_of_last_month = Date.new(now.year, now.month, 15).prev_month
=> Sun, 15 Sep 2019

Now that we have the 15th of last month saved as the_15th_of_last_month and the most_recent_episode_publishing_date, we can compare them to know if this episodes is more recent than the last 15th of the month:

pry(main)> most_recent_episode_publishing_date > the_15th_of_last_month
=> false

This means that our most most_recent_episode_publishing_date was published before the 15th of last month. As I only want episodes published in between the last 15th and today, I’ll not add this to the Invoice association.

The logic can be flipped around however you want to use this tool. Enjoy!

Build an Algorithm Processing Website

Why Care?

A friend of mine was interested in an idea for beating the casino at roulette.

His theory is that if he keeps playing either red or black, but adding to the bet, there is a mathematical certainty of winning at some point.

First spin, go red with $10.

Second spin, go red with $22.

Third spin, go red with $33.

Or something like that.

I told him I could write a program that would tell him the number of consecutive results from 50/50 roulette spins.

This is how we did it:

Tutorial For Launching Simple Algorithm Tools

Learning Algorithmic Technology

At this tutorial’s core, this is an HTML5 tutorial.

HTML5 incorporates HTML and JavaScript together. HTML5 incorporates CSS as well, but this tutorial doesn’t discuss that because design hasn’t been addressed here.

This tutorial takes the watcher on a journey of creating a simple web tool. In it we:

  • Start a project using command line interface (CLI) tools
  • Write the JavaScript algorithmic logic for the probability
  • Write the HTML5 user input form and clickable submit button
  • Link the JavaScript algorithm and the HTML5 input to work as a graphic user interface
  • Write clear directions for what the tool is used for
  • Initialize the project as a git project (version history software)
  • Sync our project with a GitHub repository
  • Publish the tool using GitHub pages

The tool is now available on the internet to whomever cares to view it. Click here to check it out:

www.ianrobinson.net/roulettespinner

If I were to answer my buddies specific question, this tool need more work. We would need to incorporate the increments of betting in order for us to get a specific plan to beat roulette…. but at the end of the day, this isn’t about beating the casinos. Even if we started beating casinos, the casinos would just kick us out.

The cool thing about this is that it helps us think algorithmically about complex issues. Using computers as tools, we can run massive tests in the blink of an eye. My computer only starts to have slow results (requiring 2-3 seconds) around 100 million spins. Imagine how long it would take to do 100 million spins in real life.

Algorithms are fun.

Fixing “Single arity template handlers are deprecated” error when upgrading from Rails 5.2 to Rails 6.0

DEPRECATION WARNING: Single arity template handlers are deprecated. Template handlers must
now accept two parameters, the view object and the source for the view object.
Change:
  >> Coffee::Rails::TemplateHandler.call(template)
To:
  >> Coffee::Rails::TemplateHandler.call(template, source)
 (called from at /Users/MediocreManta/Desktop/freedom_podcasting/Rakefile:6)

This was an error I encountered while upgrading my application from Rails 5.2 to Rails 6.0. I found the fix on this Github page, but I thought I’d write it out here to make it a bit clearer for the young programmers out there.

To fix it, I upgraded the coffee-rails by doing the following:

  • Open Gemfile
  • Change gem 'coffee-rails', '~> 4.2'` to `gem 'coffee-rails', '~> 5.0.0'
  • Stop server in terminal by pressing ctrl + s
  • Running the command bundle
  • Restarting the server with rails s

Hope this helps!

I’ve added some language to the Rails documentation via this PR. Hopefully the powers that be accept the addition so future generations can skip having to look this up.

Comma Separated List of Array – Good idea for Ruby on Rails?

I feel like there should be a rails function for doing a comma separated list from an array. Here’s how to do it explicitly:

<% search_tags.each_with_index do |tag, index| %>
  <% if index < search_tags.size - 1 %>
    <%= "#{tag}, " %>
  <% else %>
    <%= "#{tag}" %>
  <% end %>
<% end %>

…maybe `render_comma_separated_list(array)` or something.

An example array would like this = [“one”, “two”, “three”]

render_comma_separated_list(array)

=> one, two, three

Does something like this exist already?

Is this worth the effort of making a PR to Ruby on Rails?

Radix Sort is Fun… but it’s Useless in JavaScript

I just spent an hour writing a Radix sort algorithm. It turns out that it is 25% the speed of the built in JavaScript `.sort()` function.

Apparently all this sorting has been figured out in the past. Strange that it’s part of learning to code these days…

const performance = require('perf_hooks').performance;


function getDigit(num, location) {
  let stringNum = num.toString();
  let resultNum = parseInt(stringNum[stringNum.length - 1 - location]);
  if (resultNum) {
    return resultNum;
  } else {
    return 0;
  }
}

function getDigitCount(num) {
  let digitCount =  Math.abs(num).toString().length;
  return digitCount;
}

function mostDigits(arr) {
  let maxDigits = -Infinity;
  for (var i = 0; i < arr.length; i += 1) {
    var digitCount = getDigitCount(arr[i])
    if (maxDigits < digitCount) {
      maxDigits = digitCount;
    }
  }
  return maxDigits;
}

function radixSort(list) {
  let numberOfDigitsTheLargestNumberHas = mostDigits(list);

  for (let i = 0; i < numberOfDigitsTheLargestNumberHas; i += 1) {
    let bucket = [[],[],[],[],[],[],[],[],[]];

    for (var j = 0; j < list.length; j += 1) {
      let number = list[j];
      bucket[getDigit(number, i)].push(number);
    }
    list = bucket.flat(2);
  }
  return list.flat();
}

function sum(a, b) {
  return a - b;
}

var ourBeautifulArray = [50000, 1200,1133, 44, 22, 1, 400000000];
var time1 = performance.now();
console.log(radixSort(ourBeautifulArray));
var time2 = performance.now();
console.log(`RadixSort took ${time2 - time1} to execute`);

var time3 = performance.now();
console.log(ourBeautifulArray.sort(sum));
var time4 = performance.now();
console.log(`Normal JS sort took ${time4 - time3} to execute`);

It’s possible that there is room for improvement in the way I’m executing this algorithm. Perhaps using .flat is causing this.

Either way, even if it’s not a useful thing to be able to do, I think it’s interesting. Once you figure out how it works, it’s neat because it sorts things in non-obvious ways.

I just wish it performed better. LoL

If you want to see the code I’m working with to deepen my knowledge of JavaScript, check out this repository.

Ruby vs. Python vs. JavaScript – What Programming Language To Learn First?

When I started programming, I struggled with deciding on a language. What programming language to learn first? How does one decide between Ruby, Python and/or JavaScript?

It’s an interesting question. I wish I could have seen the image below when I was trying to make sense of it:

FizzBuzz written in Python, Ruby and JavaScript

The three programs above all do the EXACT same thing. JavaScript on the left, Ruby in the middle and Python on the right.

All three print a count from one to fifteen. When the count is evenly divisible by 3 and 5, it prints ‘fizz_buzz’, when evenly divisible by 3 it prints ‘fizz’ and when evenly divisible by 5 it prints ‘buzz’. If none of those, it prints the number. You can see the count listed at the bottom of the image.

This is a classic computer programming exercise.

Aesthetics of Code

Whenever anyone shares their opinions on aesthetics, it’s important to remember that there are no right answers. Aesthetics are a matter of taste. So I’m just sharing my taste for code here.

The JavaScript file on the left requires considerably greater amount of keystrokes. It looks confusing. I see lots of opportunities to make mistakes.

Python is clearly the most concise. The Python code is three lines shorter than the other programs.

I like that Ruby doesn’t require semi-colons or colons. These symbols are annoying and require a close look. For me, it’s easy to mistake a semi-colon for a colon.

There is a question about how to write variables. One way is camel case (writingVariablesLikeThis), another option is to use underscore case (wirting_variables_like_this). Camel case is more concise, but I think it’s less aesthetically pleasing than the alternative.

In terms of aesthetics I can rank order the languages. Here they are from the prettiest to the ugliest (ugliest=JavaScript).

  1. Ruby
  2. Python
  3. JavaScript

Does that mean that I recommend learning Ruby as a first language?

Not really.

What Programming Language to Learn First?

Do this in order:

  1. HTML
  2. CSS
  3. JavaScript

JavaScript is the scripting language that you WILL learn if you care to write applications on the web.

All websites that have moving stuff use JavaScript.

Once you learn JavaScript, the other languages will be far easier to learn. I think switching from JavaScript to Ruby is actually interesting and fun.

If you come up learning Ruby, switching to JavaScript will seem like running with an irregularly sized weight chained to your hip.

Also, I’d suggest learning using Free Code Camp. I’m making a series of videos which I hope provide some special insights into the course work.

Enjoy!