Auto-Activating Hirb in Rails Console

Tech: Rails, Ruby, Hirb gem, CLI 

Problem: Want to auto-load Hirb gem in Rails console... in 3 different environments (Docker container, work Mac, personal Mac)... experiencing a different scenario in each environment!

Code (Docker Container)

This one was easy and worked instantly... add gem 'hirb' to Gemfile. Add .irbrc file to the project root folder. For console output configuration, add hirb.yml file to config folder.

hirb_irbrc hirb_yml

 

 

Code (work Mac MacBook Pro OS X Yosemite 10.10.5, Mid 2015)

I expected to replicate the setup locally and have success.... nope! When launching the Rails console, I still had to manually activate the Hirb gem.... after some reading, I discovered the .irbrc in this case should be in the user root directory. I navigated there, created .irbrc file... and it was no where to be found...

touch .irbrc

ls => no file! ??? 

How about ls -a ? There it is!

cli => vim .irbrc and copy in the required code (i for insert, make changes, esc, :wq), then reload cli => source ~/.irbrc

work_mac_irbrc

 

 

Code (personal MacBookPro OS X Yosemite 10.10.5, Mid 2012)

Now, I really expected this to go smoothly after the above install, but it was the most difficult of the three. In this case, I already had an .irbrc file in my root folder, so I added the Rails env code. First though, I copied the original for reference just in case. cp .irbrc .irbrc_original

original_with_rails_env

 

 

When trying to reload with source ~/.irbrc, seeing the following error:

source_error

 

After playing around with no success... back to Google. I discovered a better alternative to finding out what is wrong. I used ruby ~/.irbrc to launch the file and maybe see a different set of error msgs... hopefully, more specific...

ruby_awesome_print_error

ruby_conf_error

 

Success! Clearing out some of the erroring code allowed a successful launch of the console with Hirb auto-loaded.

final 

 

Questions remain though... 

  1. On personal mac, I was surprised to see .irbrc already in the user root folder.
  2. Not sure why those particular lines were erroring, and if by removing them, will it cause problems elsewhere?
  3. The source error remained on my personal mac although I successfully auto-loaded Hirb in the Rails console. Why?
  4. Why does Docker look for .irbrc in the project root, and local machine in the user root?
  5. I would like to explore and implement the awesome_print gem.

 

References:

http://tagaholic.me/2009/09/07/hirb-tips-for-rails.html

http://stackoverflow.com/questions/2704041/irbrc-not-executed-when-starting-irb-or-script-console

Dashing Rickshaw Pie Chart Widget Colors

Tech: Dashing, Ruby, Rickshaw, D3, JS, CoffeeScript

Problem: Dashing dashboard using the pie widget for multiple displays. Need the pie widget to display different color pieces depending on the data.

Code:

CoffeeScript – original

onData: (data) ->

color = d3.scale.category20()

CoffeeScript – solution

if data.id == ‘Object.id’

color = d3.scale.category20()

.range( [‘#2ca02c’, ‘#999999’, etc])

 

Reference:

http://coffeescript.org/

https://gist.github.com/mattia72/8168893

http://bl.ocks.org/aaizemberg/78bd3dade9593896a59d

Rails Test Framework

Tech: Rails, Ruby, Minitest, PostgreSQL

Problem: I recently attended a Microsoft CodeCamp for Angular2. Although I have heard about the importance of testing/TDD several times before, something stuck when discussing the importance of testing. I decided to implement a full test suite before coding further in a project of mine.

Code: 

CLI:

rake db:create

rake db:migrate

rake db:test:prepare

rake test

 

Gemfile – adding :test to :dev group

group :development, :test do

gem ‘spring’
gem ‘dotenv-rails’

end

 

database.yml – test mirrors development db

test:

adapter: postgresql
database: test
pool: 5
timeout: 5000

test_helper.rb – commenting out due to errors (see reference link below)

# fixtures :all

game_test.rb

require ‘test_helper’

class GameTest < ActiveSupport::TestCase

def setup

@game = Game.new(week_id: rand(1000),
away: “OSU”,
home: “Michigan”,
tiebreaker: [true, false].sample
)

end

test ‘valid Game’ do

assert @game.valid?, @game.errors.full_messages

end

test “should not save without a week_id” do

@game.week_id = nil
refute @game.valid?, ‘saved Game without week_id’
assert_not_nil @game.errors[:week_id], “no validation error for week_id present”

end

test “should not save without away team” do

@game.away = nil
refute @game.valid?, ‘saved Game without away team’
assert_not_nil @game.errors[:away], “no validation error for away team present”

end

test “should not save without home team” do

@game.home = nil
refute @game.valid?, ‘saved Game without home team’
assert_not_nil @game.errors[:home], “no validation error for home team present”

end

test “should not save without tiebreaker boolean” do

@game.tiebreaker = nil
refute @game.valid?, ‘saved Game without tiebreaker boolean’
assert_not_nil @game.errors[:tiebreaker], “no validation error for tiebreaker boolean present”

end

end

Reference:

http://guides.rubyonrails.org/testing.html#rails-meets-minitest

http://guides.rubyonrails.org/configuring.html

http://stackoverflow.com/questions/33077366/rails-failing-test-with-an-activerecordstatementinvalid-pgnotnullviolation

https://semaphoreci.com/community/tutorials/how-to-test-rails-models-with-minitest

Rails Model Boolean Validations

Tech: Rails, Ruby, PostgreSQL

Problem: Experiencing interesting behavior when testing and manually adding a record in the Rails console. After creating a record with .new, .save would rollback!

Error: console output [“Tiebreaker can’t be blank”]

Code:

Games Migration

class CreateGames < ActiveRecord::Migration

def change

create_table :games do |t|

t.belongs_to :week,     null: false
t.datetime :date
t.string :away,              null: false
t.string :home,             null: false
t.float :spread
t.string :location
t.string :start_time
t.boolean :tiebreaker,   null: false
t.string :winner
t.integer :away_pts
t.integer :home_pts
t.integer :total_pts

end

end

end

Game Model

class Game < ActiveRecord::Base

validates :week_id,     presence: true
validates :away,          presence: true
validates :home,         presence: true
validates :tiebreaker,  presence: true

end

 

Solution: Passing “false” or false for the tiebreaker attribute caused the validates presence to fail! Need to change up the validation

Solution Code: validates_inclusion_of :tiebreaker, in: [true, false]

Tip/Trick: object.errors.full_messages provides an easy to read array of error messages. The console rollbacked the transaction without displaying errors.

Reference:

http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html

http://stackoverflow.com/questions/19037733/why-does-my-rails-rollback-when-i-try-to-user-save

Rickshaw Y-Axis Stroke Color

Tech: Dashing, Ruby, Rickshaw, D3, JS, CoffeeScript, HTML, CSS

Problem: Client requests specific y-axis intervals, with a particular tick colored differently to stand out

Challenge: I have easily setup specific y-axis intervals previously (solution included below). The challenge here is having one tick colored differently. My initial solution did color the “16” tick red, but due to the Dashing framework data feed every minute, the tick reverts back to black with the next data push.

Code: 

Widget CoffeeScript => manual assignment of y-axis values

yAxisOptions =  {

graph: graph,
tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
tickValues: [5,10,15,16,20,25,30,35,40,45]

}

 

Widget HTML => initial script… timeout bc widget needs a second to populate

<script type=’text/javascript’>
$(function() {

setTimeout(function(){

$(“.widget-longest-patient .y_grid .tick”).filter(function() {

return $(this)[0].textContent === ’16’;

}).css({“stroke” : “red”, “stroke-width” : “1”});

}, 1500);

});
</script>

 

Widget HTML => implemented solution… every second the color red is applied

<script type=’text/javascript’>
$(function() {

setInterval(function(){

$(“.widget-longest-patient .y_grid .tick”).filter(function() {

return $(this)[0].textContent === ’16’;

}).css({“stroke” : “red”, “stroke-width” : “1”});

}, 1000);

});
</script>

 

Conclusion: While this does work, I believe there is a better solution out there. I want to look into assigning the tick color when it comes from the RickShaw CoffeeScript. Due to time & other project restraints, haven’t returned to this yet.

 

Reference:

http://stackoverflow.com/questions/15364298/select-element-by-exact-match-of-its-content

http://www.w3schools.com/jquery/jquery_css.asp

https://github.com/shutterstock/rickshaw/issues/188

Tomorrow Is Built Upon What We Achieve Today

A colleague of mine recently explained his 3-point matrix for considering a new dev hire: an interesting personal/side project, a tech blog, and… I totally forget the third item.

With this lapse in mind, and as a fan of Kaizen, this web log is born.  Fairly often, I find myself forgetting or being unable to recall a particular CLI or Git command, a solution to a error message I know I’ve seen before, or wondering… how did I configure this?

No more. This Tech Retrospect will serve as an online repository of error msgs/solutions, code refactors, configurations, tips & tricks, project updates, sql schemas, code challenges, stacks, etc… basically anything future-Luke will thank present-Luke for writing down!