Kang-Kyu Lee

Ruby + Rails codewriter

Read this first

export CSV by rails

I will not save a file, just make it downloaded by Tempfile.
I will not use database table, of course.

This is how my form looks (in new page)
config/routes.rb file

resources :accounts, only: [:new, :create]

app/views/accounts/new.html.erb file

<%= form_with url: accounts_path, local: true do |f| %>
  <%= f.text_area :names, rows: 10, required: true %>
  <p>Add account names separated by newline.</p>
  <%= f.submit 'Export CSV' %>
<% end %>

When the form is submitted, it triggers create action. Form submit of form_with makes POST request to accounts_path with parameters. And rails syntax resources :accounts makes create action of accounts controller triggered by that POST request.

And this is not a model backed form. Sometimes simple things look difficult or not possible because the other complicated things look too easy. ActiveRecord is not needed (something like @account in the...

Continue reading →

레일스로 코딩 배우기

나는 루비가 코딩을 배우기에 좋은 출발점이라고 생각한다
Learn To Program 이라는 책을 읽어보라 https://pine.fm/LearnToProgram/

물론 어느 programming language 로 시작하든지 코딩을 배우는 것은 인생에서 매우 중요하다고 생각한다

그리고 루비를 배우기에는 레일스가 좋은 출발점이라고 생각한다
지금 시작해보자

rails new app_name
cd app_name

레일스의 기본은 scaffolding 이다 (한국말로는 “비계"라고 함) 그러므로 한번 따라가보자

rails generate migration create_cups name size
rails db:migrate

cups 는 여기서 테이블의 이름이다
테이블은 데이타베이스를 배울 때 나오는 말이다


class Cup < ApplicationRecord

이렇게 하고

class CupsController < ApplicationController
  def index
    @cups = Cup.all

이렇게 하고

resources :cups

이렇게 하고

<% @cups.each do |cup| %>
  <%= cup.name %>
  <%= cup.size %>
<% end %>

이렇게 하면 화면에 컵의 목록을 볼수가 있다
물론 (중요하지 않은) 많은 것을 생략하였다

중요한 것은 @cups 가 컵의 목록을 가지고 넘어간다는 것이다
그래서 instance variable 이라고 한다

잘 생각해보자
데이타베이스의 테이블이 가지고 있는 컵의 목록이 브라우저 화면으로 나오게 하는 것이 이와 같은 패턴으로 이루어진다는 것을

이것이 레일스의 기본이다

생략한 것 중에서 코드가 들어가는 자리는 다음과 같이 확인할 수 있다...

Continue reading →

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

require "minitest/autorun"

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

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.



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.


so I opened Rakefile and added this line.

t.options = "--pride"

it works!

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"]

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

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

BOTH of two options. why not?


First let’s make API part

we need players to render JSON


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


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

and route


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

on different terminal window,

$ curl 'http://localhost:3001/movies'

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.


Continue reading →


Doc Rdoc ..




ri Arrayeach

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

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

Change it into

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


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
 => nil

and so on. Nobody quits at this point.

v = 1+2
puts v
 => 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
 => 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
say(1, 2)
 => nil

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

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.


gem install guard guard-shell
guard init shell


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

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


!/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
$ guard

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

Continue reading →