Kang-Kyu Lee

Ruby + Rails codewriter

Read this first

I wrote merge sort in Ruby

I am learning sorting algorithms these days. And to me merge sort looks simple than other sorts. (There are merge sort, insertion sort, quick sort, selection sort, bubble sort, et cetera.)

I thought I should try to write it in Ruby.

The steps of the merge sort are:

  • First, split the array (yes, I’m sorting an array of numbers) into two halves.
  • Second, sort those two arrays.
  • And then, merge the two sorted arrays and update original array, in the order of “small number first”. (yes, I’m sorting it in ascending order)

As always, I am writing a test first (lol) because I like to see some tests are passing.

class Sorter
  def self.merge_sort(array)
    array.sort # make the test pass
  end
end

require "minitest/autorun"

class SorterTest < Minitest::Test
  def test_merge_sort
    array = [2, 1, 3]
    assert_equal [1, 2, 3], Sorter.merge_sort(array)
  end
end

I am going to name the...

Continue reading →


Add pride option to rake

ruby -Itest test/something_test.rb --pride

I use --pride all the time because it gives a rainbow when successful.

but

rake

does not have the rainbow. so I found I could add TESTOPTS

rake TESTOPTS='--pride'

but I wanted make it as default. After some google search, I went to source code.

https://github.com/ruby/rake/blob/master/lib/rake/testtask.rb

so I opened Rakefile and added this line.

t.options = "--pride"

it works!

# Rakefile
require "bundler/gem_tasks"
require "rake/testtask"

Rake::TestTask.new(:test) do |t|
  t.libs << "test"
  t.libs << "lib"
  t.options = "--pride"
  t.test_files = FileList["test/*_test.rb"]
end

task :default => :test

View →


React with Ruby on Rails 5.1

$ ruby -v
ruby 2.4.1p111
$ rails -v
Rails 5.1.4

$ brew install yarn --without-node
$ yarn -v
1.0.2

$ rails new scoreboard --webpack=react --api

BOTH of two options. why not?

https://yarnpkg.com/en/docs/install#alternatives-tab

 First let’s make API part

we need players to render JSON

# db/seeds.rb

movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
$ rails generate model Movie name:string
$ rails db:migrate
$ rails db:seed

now ApplicationController inherits ActionController::API

# app/controllers/movies_controller.rb

class MoviesController < ApplicationController
  def index
    render json: Movie.all
  end
end

and route

# config/routes.rb

  get "/movies", to: 'movies#index'
$ rails server -p 3001

on different terminal window,

$ curl 'http://localhost:3001/movies'
[{"id":1,"name":"Star
...

Continue reading →


buzzword bingo with Rails

I ran into “Integrating Elm with Rails 5.1” post on Pragmatic Studio blog a month ago.

And then I wanted to use this Rails setting while watching Pragmatic Studio Elm course. In the video, what is used was node server.js. I preferred not to understand how it works, so I did the same thing in Rails.

This is what we need at the lesson. It’s not other than just rendering JSON with 5 random buzzword entries in the back-end. For example:

[
  {
    id: 3,
    phrase: "In The Cloud",
    points: 300
  },
  {
    id: 8,
    phrase: "User-Centric",
    points: 175
  },
  {
    id: 2,
    phrase: "Doing Agile",
    points: 200
  },
  {
    id: 10,
    phrase: "Synergize",
    points: 375
  },
  {
    id: 4,
    phrase: "Rock-Star Ninja",
    points: 400
  }
]

In app/controllers/entries_controller.rb, following is what I did. This code is rendering 5 random entries as JSON.

class
...

Continue reading →


ri

Doc Rdoc ..

https://www.omniref.com/ruby/gems/httparty/0.13.1/symbols/HTTParty::ClassMethods/default_params

http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest/Assertions.html#method-i-assert_equal

http://www.rubydoc.info/gems/minitest/5.8.3/Minitest/Assertions#assert_equal-instance_method

ri Array#each

If you have still this in ~/.gemrc file (still works)

gem: --no-ri --no-rdoc

Change it into

# ~/.gemrc
install: --no-document
update: --no-document
gem: --no-document

because we have this new flag, and the old --no-ri flag has been deprecated.

-​-[no-]document [TYPES] - Generate documentation for installed gems List the documentation types you wish to generate. For example: rdoc,ri

However if you have it this way, you can have ri command for all gems with you.

--document ri
--no-document rdoc

http://ruby-doc.org/
http://www.rubydoc.info/

To update, I found ri...

Continue reading →


Try blocks

 try Block

…hitting the wall? then stop learnng Ruby, and come back any time. This is how I learned Ruby coding.

I started with Chris Pine book, which starts with puts in Chapter 2. ('Hello World' shows in the Introduction, but that’s not where I started) So that’s why my first Ruby code was:

puts 1+2
# 3
# => nil

and so on. Nobody quits at this point.

v = 1+2
puts v
# 3
# => nil

variable, parameter, argument, object… and block.

{ puts 1+2 }

This is a block. It’s “chunk of code” (When I google “chunk of code” and it shows Wikipedia Block on top… Maybe “chunky bacon” comes from it)

def say
  puts 1+2
end
say
# 3
# => nil

This is a method. You can call a method with method arguments, and it’s nice because you can change those parameters from outside of method definition.

def say(a, b)
  puts a+b
end
say(1, 2)
# 3
# => nil

Likewise, it would look nicer if you can call it...

Continue reading →


PostgreSQL for Rails on Apple OS X

This could be a short tutorial to follow along, how to setup PostgreSQL for your development environment. Basically it’s going to be a sharing my experience about, when I tried to understand more of it from my Rails Meetup Study Group.


I’ve done it on Apple machine, so started with following (Just in case, starting this with brew updating)

brew update && brew upgrade
brew install postgres

Of course it should be done after you install homebrew package manager first if not done yet, and for me I simply followed their easiest way on brew.sh page.

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Check if following psql command working. (you will see your username of the machine in place of your_username, and more lines omitted here.)

$ psql --help
psql is the PostgreSQL interactive terminal.

General options:
  -d, --dbname=DBNAME
...

Continue reading →


exercism.io with Guard-Shell

I’m enjoying exercism.io like anybody else. Inspired by Ruby Koans with guard shell I set it up for my practicing.

Please comment at my gist for any further suggestions.

In the ~/exercism/ruby directory, add two files Guardfile and Rakefile after install the guard-shell gem.

 Terminal

gem install guard guard-shell
guard init shell

 Guardfile

guard :shell do
  watch(/^(.+)\.rb$/) do |m|
    `rake test TEST="#{m[1].chomp('_test')}_test.rb" TESTOPTS="--pride"`
  end
end

I added pride option because it colors a rainbow when success!

 Rakefile

#!/usr/bin/env ruby
# -*- ruby -*-

require 'rake/clean'
require 'rake/testtask'

task :default => :test

Rake::TestTask.new(:test) do |t|
  t.libs << "test"
  t.test_files = FileList['**/*_test.rb']
  t.verbose = true
end
$ guard

And then run guard on ~/exercism/ruby directory prompt. Now whenever I make changes onto the exercise files in...

Continue reading →


Ruby block

I’ve been trying to figure out how it works. This morning I wanted to write it down my thinking process today, before I forget.

block_given?

block_given? is a method of Kernel module. In other words, it’s one of the same kind of puts, gets, sleep, etc. They are at the top-level, so to speak.

The Kernel module is included by class Object, so its methods are available in every Ruby object.

And block_given? verifies if block is given when you call a method.

What do you mean by “block is given”? In normal cases (when block is not given) the codes should be like this:

object_name.method_name(parameters)
object_name.method_name

Here you call methods with parameters, or without parameters. But when you say “block is given” (However this is also normal, nothing special) that means you called it with a block. A lot like a parameter.

object_name.method_name(parameter_names) { chunks of
...

Continue reading →


Rails, datepicker

= form_for @task do |f|
  = f.datetime_field :done_at
  = f.text_field

I thought because done_at should be saved as DateTime, the field should be datetime_field. But text_field works fine.

On top of that, for some browsers (Firefox, I can say) date type of input tag gives you a datepicker on its own (html5 datepicker), and I didn’t want to have them.

<input id="task_done_at" name="task[done_at]" type="datetime" />

Most of all, I watched an episode of Railscasts and that’s why I started working on it.

I used jquery-ui-sass-rails gem.

I put this file app/assets/javascripts/tasks.js.coffee as following the screencast #213

jQuery ->
  $('#task_done_at').datepicker
    dateFormat: 'yy-mm-dd'

also after setting up

gem 'jquery-ui-sass-rails'

//= require jquery.ui.all
//= require jquery.ui.datepicker

@import jquery.ui.core
@import jquery.ui.theme
@import jquery.ui.datepicker

and...

Continue reading →