An object oriented tictactoe game

Just doing a basic Ruby tictactoe game using some basic oop.  Feel free to copy and paste this code and give it a go.

# tic tac is a 2 player board game played on 3 x 3 grid.
# players take turns marking a square, the 1st player to mark 3 in a row
# wins.

# Nouns: player, board, square, grid
# Verbs: play, mark

# board
# square
# player
# – mark
# – play
require ‘pry’

class Board
attr_accessor :board, :squares, :marker
WINNING_LINES = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +
[[1, 4, 7], [2, 5, 8], [3, 6, 9]] +
[[1, 5, 9], [3, 5, 7]]

def initialize
@squares = {}

def reset
(1..9).each { |key| @squares[key] = }

def get_square_at(key)

def set_square_at(key, marker)
@squares[key].marker = marker

def []=(num, marker)
@squares[num].marker = marker

def unmarked_keys { |key| @squares[key].unmarked? }

def marked_keys { |key| @squares[key].marked? }

def full?

def someone_won?

def count_human_marker(squares)

def count_computer_marker(squares)

def three_identical_markers?(squares)
markers =
return false if markers.size != 3
markers.min == markers.max

def winning_marker
WINNING_LINES.each do |line|
squares = @squares.values_at(*line)
if three_identical_markers?(squares)
return squares.first.marker

# rubocop:disable Metrics/AbcSize
def draw
puts “”
puts ” | |”
puts ” #{@squares[1]} | #{@squares[2]} | #{@squares[3]}”
puts ” | |”
puts “—–+—–+—–”
puts ” | |”
puts ” #{@squares[4]} | #{@squares[5]} | #{@squares[6]}”
puts ” | |”
puts “—–+—–+—–”
puts ” | |”
puts ” #{@squares[7]} | #{@squares[8]} | #{@squares[9]}”
puts ” | |”

class Square
attr_accessor :marker

def initialize(marker=INITIAL_VALUE)
@marker = marker

def to_s

def unmarked?

def marked?

class Player
attr_accessor :marker, :player_win_count, :computer_win_count

def initialize(marker)
@marker = marker
@player_win_count = 0
@computer_win_count = 0

class TTTGame

attr_reader :board, :human, :computer

def initialize
@board =
@human =
@computer =
@current_marker = FIRST_TO_MOVE

def game_winner_found
if human.player_win_count == 5
puts “Congrats, you won against the machine!”
elsif computer.computer_win_count == 5
puts “Skynet wins.”

def play

loop do

loop do
break if board.someone_won? || board.full?
break if game_winner_found
break unless play_again?



def display_welcome_message
puts “Welcome to tic tac toe!”
puts “”

def display_goodbye_message
puts “Thanks for playing Tic tac toe! Goodbye!”

def clear
system ‘clear’

def clear_screen_and_display_board

def display_board
puts “You’re a #{human.marker}. Computer is a #{computer.marker}”
puts “”
puts “”

def joinor(arr, delimiter, word = “or”)
arr[-1] = “#{word} #{arr.last}” if arr.size > 1

def human_moves
puts “Choose a square (#{joinor(board.unmarked_keys, ‘, ‘)}):”
square = nil
loop do
square = gets.chomp.to_i
break if board.unmarked_keys.include?(square)
puts “Sorry, that’s not a valid choice.”
board.[]=(square, HUMAN_MARKER)

def defense(line)
if board.squares.values_at(*line).join(‘, ‘).count(‘X’) == 2{ |k,v| line.include?(k) && v.marker == ‘ ‘ }.keys.first

def offense(line)
if board.squares.values_at(*line).join(‘, ‘).count(‘O’) == 2{ |k,v| line.include?(k) && v.marker == ‘ ‘ }.keys.first

def computer_moves
square = false

# defense
Board::WINNING_LINES.each do |line|
square = defense(line)
break if square

# offense
# if !square
# Board::WINNING_LINES.each do |line|
# square = offense(line)
# break if square
# end
# end

if !square
# square = board.[]=(board.unmarked_keys.sample, COMPUTER_MARKER)
square = board.unmarked_keys.sample

# board.squares[square].marker = COMPUTER_MARKER
board.[]=(square, COMPUTER_MARKER)

def current_player_moves
if @current_marker == HUMAN_MARKER
@current_marker = COMPUTER_MARKER
@current_marker = HUMAN_MARKER

def reset
@current_marker = FIRST_TO_MOVE

def display_result
case board.winning_marker
when human.marker
puts “You won!”
human.player_win_count += 1
when computer.marker
puts “Computer won!”
computer.computer_win_count += 1
puts “It’s a tie”

def play_again?
answer = ”
loop do
puts “Would you like to play again? (y/n)”
answer = gets.chomp.downcase
break if %w(y n).include? answer
puts “Sorry, must be y or n”

answer == ‘y’

def display_play_again_message
puts “Let’s play again!”
puts “”

game =


creating a ruby gem

So i had a Votable module in my rails app that a few of my model classes were using.  Say I had other rails projects that could use this module, and you want to make it so that if you edit this module you wouldn’t have to go to other applications and change the code there as well.  So you could also create a gem for this module, install it like you would any other gem and delete the module I was using in my application.  So here is how that works.

First lets register at, it’s free to signup and simple.  Once you signup you need to have a gem called gem cutter installed in your computer.  So ‘gem install gem cutter’ and bundle install.

Then go to a new folder and create a new folder like so, mkdir votable.  Inside that folder create a gem spec file called whateveryouwant.gemspec i’ll name it votable.gemspec.  Then we give it some specifications like shown below. do |s| = ‘votable’
s.version = ‘0.0.0’ = ‘2015-11-02’
s.summary = ‘Votable module for voting feature in postit app’
s.description = ‘A voting module gem’
s.authors = [‘Brian Jin’] = ‘’
s.files = [“lib/votable.rb”]
s.homepage = ‘’
s.license = ‘MIT’

  • Don’t worry about the homepage right now.  Normally you want your code inside a github repo and you can fill out the url for that page.
  • the s.files is important, give it the directory of the ruby file we are about to create, which should be inside a lib folder.

Create a lib folder, mkdir lib.  Inside of this lib folder create a ruby file votable.rb.  Our code will be entered here.

In the votable.rb file I will just copy and paste my module that I had in my application shown below.

module Votable
extend ActiveSupport::Concern

included do
has_many :votes, as: :votable

def total_votes
self.up_votes – self.down_votes

def up_votes
self.votes.where(:vote => true).size

def down_votes
self.votes.where(:vote => false).size


Switch over to the terminal.  Because we have the gem cutter gem installed we can use this command to create out gem.

gem build votable.gemspec

This will produce a .gem file.

Now I can push this to and make it available for download.  It will also ask for your user credentials you created earlier.

gem push votable-0.0.0.gem

Now type

gem list -r votable

You can see that it lists your gem already.  Go to and you can already see your gem.

Now I go back to my application and delete the module I just created a gem for.  Then I can add the gem in my gem file and bundle install.  Restart the server and you should see a working application with the same features as before.

If I were to debug errors and make changes on the gem I created, I can edit the ruby gem and save, then edit the version number on the gemspec file to 0.0.1 for example.  Then issue the command gem build votable.gemspec again and it will create a new version of the edited gem as 0.0.1.  Then I will push this using this command

gem push votable-0.0.1.gem

Now I just change the gem in my application to say version 0.0.1 and bundle install.

But this not a great work flow, every time you have a bug and make a change you have to go and update the version of your gem and deploy it.  That makes testing and fixing bugs very painful.  So instead you can work on it locally and tell your rails app that this is local.  We do this by specifying with a path parameter after the gem and give it the address where the gem lives.

gem ‘votable’, ‘= 0.0.1’, path: ‘/Users/somepath/to/your/gemfile/votable’

Then bundle install.  Now we can work locally on any changes for this gem.

There is more detail on option on the rails guides site


Why you don’t need Devise. Get a better understanding of authentication!

Devise gem comes with a lot of extra features you don’t need.  What happens is you end up learning everything about using a specific gem and neglect to understand how to learn how to create an app with rails.  First a few things on authentication.  Your app should never know your password, it shouldn’t be able to find it or even decrypt it.

You should save your password as a One-way hash.  So we don’t decrypt it, but instead turn it into a string, stored as a hash, and match those hashes.  That is how password authentication works, a one way authentication.  Other methods are more prone to attack.

Say we already have a basic user class with some basic attributes.

1- We need to add a column to store and keep the long token, we must call it password_digest since we are using ruby has_secure_password. (shown later)

rails g migration add_password_digest_to_users

in the migration file

def change

add_column :users, :password_digest, :string


2- Go to your User model and add this line, has_secure_password

3- Add gem ‘bcrypt’, version 3.0.1.  This gem has the library that does the actual hashing.  errors might arise make sure to use the right version.  There is a lot of math involved in hashing algorithms, bcrypt comes equipped.  Remember to bundle install.

Now we can test it out on rails console.

>> u =

>> u.username = ‘bob’

>> => gives you false, why?

>> u.errors => password cant be blank

This occurs because has_secure_password has some rails built in validations.  Once again rails is doing more than we want.  To bypass this is just add ‘validations: false’ to the User class

has_secure_password validations: false

>> => true

The has_secure_password gives us the password setter method

>> u.password = ‘password’


– If you look at the SQL statements created by the above.  You see it didn’t save password but the password_digest.  Password is a virtual attribute, it’s a setter, and it allows us to set values into the password digest.  Where it automatically hashes it for us using bcrypt.

So in the database you will see some long crazy string.  This is the result of our one way hash. So we have a setter method, but do we have a getter method?  The answer is no.

Log out of the rails console and relog back in.

>> u= User.find_by username: ‘bob’

>> u.password => nil

You might have seen a value for u.password before you logged out of rails console before but that is because it was ‘in memory’.

So now knowing this, how do we authenticate our application?

We just performed a one way hash on a string.  Which produces our really long token, and if those tokens match then it means those strings are correct.

– has_secure_password also gives us

>> u.authenticate(‘teststring’) method, which just gives us true or false.  If the hash tokens don’t match they return false.  If they match they return the user object, which evaluates to true.

>> u.authenticate(‘password’)

=> user object…

That’s the way we can use has_secure_password to introduce authentication to our rails app.

Tagged , , ,

Don’t delete your migrations!

Rails migration pushing issues

Say you deleted a migration so when you push all your migration histories to heroku

it gives you migration errors.

You can type

rake db:migrate:status

This will give you history of migrations and whats missing,

 Status   Migration ID    Migration Name


   up     20150207013411  ********** NO FILE **********

   up     20150207020939  Create users

   up     20150207021329  Add user id to posts

   up     20150207022740  Create comments

   up     20150207023755  Create categories

   up     20150207063021  Add columns to users

   up     20150207075531  Create post categories

   up     20150208061306  Add column to posts

   up     20150217172541  Add pass word digest to users

   up     20150305203015  Create votes

   up     20150309223946  Add column to comments

  down    20150313162219  Create posts

you can then copy that migration ID and create a new file in your migrations with that migration ID number, and code inside the file.

This will put that code in the proper place so you can run migrations smoothly on heroku or locally.

mysql database creation questions!

This post is going to be broad and fragmented, so forgive me.  I have been using rails to create databases with active record for my projects which is basically a builtin feature in Rails that helps with your database table creation.  It allows you to use ruby for your database and rails conventions takes care of the rest.  But there are still many times you will need to know SQL in more specific senarios such as redoing old sites into rails and perhaps to maximize performance N+1 query problems.

When building a SQL database you it helps to obviously use a diagram whether by hand or with some program like mysql workbench.  This helps you set the tables visually, make the associations between tables, and get a broad look at what you are creating.  If you follow the programs conventions it will even write the SQL statements for you.

I know there are many books out there but I when ask more experienced developers what I should read to better my understanding of actually creating a working database for some project I get blank stares.  It looks like the process isn’t well documented it is just something you have to learn by experience.  The fundamentals and syntax to guide you, the rest are a few tips here and there, but mostly experience.  Which frustrates the heck out of me, because that takes time!  Anyway here are a few tips from blogs I’ve read, maybe it will help you guys!

– what is the nature of your application, Transactional or Analytical?

Transactional meaning more of a CRUD app, such as a blog, or store application with buying and selling.  Where the end user will be creating, updating, deleting records.  Analytical applications are more for reporting, analyzing.  They typically have less inserts, and updates.  For this database you want to get and analyze data with priority being speed for those actions.  This will affect your decision to go for a more normalized table structure or not.  Analytical databases can benefit form having more de-normalized structure.  Of course situation dictates.

I’ll put up more tips on future posts.

Keep moving

– won

Running a Rails application on Openshift server tutorial

Before we start this short tutorial you must make sure you have ruby and then ruby on rails installed on your local machine.  Type in ruby -v  to see which version you have, then type rails -v to see the version of rails you have.  If not you must install them, installing ruby and then rails can be a pain so make sure to read the documentation and when you run into problems just copy and paste the errors so you can google it.  Someone else has already solved your issue and posted it online.


Some of these commands won’t work so type sudo before those commands.

If you just added gems to your gem files make sure you type bundle install after(making sure you are in the correct app directory).  Then restart the rails server to use those changes.

To start rails server type: rails server

Or for short type: rails s

MongoDB must be running in the background so make sure you download mongodb and open up a terminal then type: sudo mongod

then press command tab to open up a new terminal tab, since we don’t want to close out the mongod server by accident.  To shut down the server press control C to properly kill the server.



Now to create a rails applications on our openshift account.

Go to your Openshift account and login.  You will create your application by selecting Rails cartridge, the Github repo is already filled in so leave it there and give the app a name.  Click create application.

We will be running our Rails app with a MongoDB as our database.  To do this just add MongoDB cartridge once openshift is done creating your app.

We don’t need the files that were automatically created for us when creating this app so you can go to your app folder and manually just highlight all the files and delete them, or simply on the terminal (make sure your inside your new app directory) type

sudo rm -rf *

The sudo part just gives you authorization to do more administrative changes to the files on your computer (Be very careful where you use that command it will delete files you might not have intended to delete, make sure your in the correct directory!!!).

Now that all the files were removed we need to add our files by either cloning the repo that we will work on from

or just run on terminal:  git remote add upstream -m master 

git pull -s recursive -X theirs upstream master

That will give you the code for this sample project to get us more familiar with using rails as our framework.  Go ahead and save your changes with git add -A, and git commit -m “”, then push to your repository.

In this case:  git push upstream master


If you want you can also create your rails app just on the terminal, by typing:

rhc app create ruby-1.9 -a yourappname

(this will already clone the app to our local machine, you can check your folder for the new files)

Then add our MongoDB database by typing:

rhc cartridge add mongodb-2.4 -a yourappname

Now make sure to work out of our new app directory so cd into your new app directory.



Next step is to login using ssh to our openshift server.  We do this by going to our app on openshift, clicking on the right side you will see this message

Remote Access

click on it and copy the ssh secret code shown.  Now paste that on your terminal and press enter, this will let you run a Secure shell session ssh on your openshift server.

Now on terminal type ls to see a list of your files.  Then we need to run the command rake secret in the app-root/runtime/repo  folder so to get there just cd into app-root, then cd into runtime and cd into repo then type rake secret, it should look like this.

cd app-root

cd runtime

cd repo

Or do it all at once: cd app-root/runtime/repo

rake secret

Once that’s done it will give you a long secret key copy that.  (command C)


Then type:  rhc setup

That will give you a list of app names, look for the one you just made.

Now type:

rhc set-env SECRET_KEY_BASE=yourSecretCodeFromTheServerWeJustGot -a yourOpenShiftAppName

Now we must restart our app by typing:

rhc app-stop yourOpenShiftAppName rhc app-start yourOpenShiftAppName


Finally after this if you go to your open shift account and click on your app it should work!  Good job if you’ve made it this far!

-keep moving




Tagged , , ,

CSS and HTML refresher!

This is my basic refresher to HTML and CSS, I will try to go over some basic information to get you started with creating your own html content, and you can learn the rest as you go along.  There are tons of references online!

First go make a new folder in your computer, and create a new file saved with a .html extension, such as index.html.  Now open that file up in a text editor like sublime, typically all html pages start off with the version of html

<!doctype html>

that signifies that we are using HTML5.  Don’t worry about the why just remember to type that in for now.  If your curious you can google it.  

Web pages are created with html tags, tags are started off with something like <body> and when the content in the body is finished the tag is closed off with </body> , notice the foward slash indicating that the tag is finished.

Pages are usually formatted as shown below.  I didn’t use good indenting but you should, because it shows relationships between each element, and whether they are direct descendants or siblings of each other.  

<!doctype html>



  <title>My website</title>

  <meta charset=”utf-8″/>



    <h1>some text</h1>

    <p>the  h1 tag above stands for header level 1 element, generally its the top most heading, receives the most weight, and search engines may rank your site according to the description here.  Notice below the h1 tag is closed out.  Right now we are in a paragraph tag.  How does the browser know whether some text should be bold, or specific font weight, or size?  Well browsers have default styling in place.  It is up to us to override it to create the pages in<em> our</em> image.  The em in between the word ‘our’ gives emphasis or makes that text italic.  Strong elements are used to bold out <strong>contents</strong>, html describes your content.</p>

     <p>reach me here at my <a href=”” target=”_blank” >site</a>.  Notice the anchor tags between the word ‘site’.  This is so I can create a clickable link.  To make a link type in href=”” with your site address.  </p>  

<img src=”img/photo.png” alt=”photo”/>

<p>  Above is the syntax for putting images on your site.  Is is similar to linking, but instead of href we use src =”” which stands for source.  So you would save an image file to your project folder under a folder that you created called image for example.  Now it is good practice if you are linking to an image that you pay for that image and not hot link to the web address of that image.  Linking to an actual address isn’t fair to the owner of that site because you are using their server to link to that image.  Instead you should download that image into a image folder in your project, then you can link to that directory.  The alt= “” is used as a description of the image incase it doesn’t show.</p>



You will notice in different html elements sizes or indentations may be different.  How do we override the default attributes that html gives us?  We use CSS and style attribute tags.  Lets say we have a paragraph tag that is linking to a page.  To apply some CSS styling to it we will use a style attribute.  

Notice below there is a anchor tag attribute that links to mysite.html.  In the style attribute we can use CSS, such as color:blue;, this just a statement that says “get the color: make it yellow”.  You can use rgb values for example color: rgb(10,200,20);, or hex values for example  color:#e3e3e3; .

<p><a href=”mysite.html” style=”color: blue;  text-decoration: underline;”>Click here!</a></p>

Notice I added more styling attributes like text-decoration, and there are many more such as background-color:, font, etc.  This is an example of inline CSS where you are mixing styling with presentation and as you can see it can get really messy, imagine all your html having styling like this on every line!  You wouldn’t be able to read your code.  You shouldn’t use this method to often.  

Instead use a style sheet.  All you have to do is create a new folder in your project called style or what ever you want, then make a new blank file, give it a name and save it as a .css.  So now you can keep your html file clean by referencing specific html elements and giving it CSS styling in another file.  This also allows you to make easy changes in your styling.  Instead of having to edit through every element in your html you can just edit it once in the style sheet, all those attributes will filter down to the specific class, id, or element you chose.  

This is the external style sheet method.  Now say we made this new style.css file with our CSS changes but our index.html file isn’t changing.  Well that is simply because the browser doesn’t know that we want to pull in the styling from that new file, we have to link to it to let the browser know where our changes are coming from.  So in your index.html file you will provide a link to that file in between the <head> </head>portion of your index.html file.  


      <link rel=”stylesheet” href=”style.css”>


In your style sheet you must be specific about the css changes and what elements they are to affect.  This is an example of a CSS style sheet called style.css. 

p {

        color: red; 

        font-family: arial;


The ‘p’ before {  } represents the element paragraph tag, what ever is inside the brackets is the CSS.  You can apply commas between for multiple elements.

img, p, h1  {

        color: red; 

        font-family: arial;


Selecting multiple elements using commas can be bad practice, it is applying attributes for every single element on the page that you chose.  What if I had another image or paragraph later.  Instead wrap material that are related in a div tag in the index.html file as shown below.  

Be sure to close out those divs or you can have problems later on.





    <img src=”” alt=”picture”/>


Now in your CSS style sheet style.css file you can provide styling for that specific division.  

   div {   

          color: red;  width: 500px; margin:auto;

          font-family: arial;



Internal style sheet is used when a small area has a unique style, or maybe it is just a small change that you want to complete that won’t make the html file look to messy.  To use internal style you just make a style tag inside the header section of the html page.  



      p {margin-right: 10px;}

      body  {background-image: url(“image/pic.png”);}




To target a very specific element lets say you have an unordered list <ul> and list items <li>, you can specify an item by giving it an ID.  We use an Id to target only one element.  I’ll use internal style sheet to edit the CSS.   Use ‘#’ to indicate ID is being used in style sheet.  



      #rah {

          color: green;







   <li id=”rah”>milk</li> 








We use classes to target a group of elements.  Use ‘.’ to indicate class.



      .rah {

          color: green;







   <li class=”rah”>milk</li> 


   <li> class=”rah” juice</li> 




Because of Cascading order if there is more than one style for an html element, the styles will cascade in a funny ways according to priority.  With Inline style being highest priority.    

1-browser, 2- external style sheet, 3- internal style, 4- Inline style  


Tagged ,


Finally put something in my github account I created months ago, and it just sat there!  Will be posting a lot more stuff on there soon.

Started a new course on web/ app development.  So far it is jumping in head first into front end, setting up a domain, server, and working with version control open source cloud application platform called openshift.  We are creating our own model of a really basic app, that needs tweaking so it can be more user friendly and pleasing to the eye.  

I got a week to come up with a mockup site using bootstrapping and just finding templates online to cut and paste features and attributes.  Then we will work on the back end, and putting it all together. 

I’ve been doing a ruby on rails tutorial on the side as well.  

Summer is so far starting off very busy!  All going to plan haha.  

Meet ups later on to learn anything else I feel I need to catch up on, had my eye on a few rails meetups and a few front end meets.  

need a beer..

Developer by spring 2015 or bust!

Well maybe I shouldn’t say bust, i’ll never quit but it’s a good way to set a timeline and keep myself under some pressure.

Two more weeks then finals!  I can’t wait for this to be over so I can start focusing on development!!

My summer plans are to learn front end, back end, and phone gap to create some apps.  Learn rails on the side and hitting up as many meet ups in the city as possible.  It’s going to be busy, but my goal is to become a junior developer by spring 2015!  I got my goals set, and i’ll have to see whether I’ll attend school next fall semester, possibly do 1 or 2 classes so I can focus on creating applications and websites for my profile.  

I know for sure that I can’t go full time at school and expect to learn web development.  There is not enough time to take 4 computer science classes and have room for anything else.  So i’ll have to tweak my approach but very excited for the rest of this year.  Good luck to all you guys trying to become developers as well!