Kang-Kyu Lee

Ruby + Rails codewriter

Read this first

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 →


Authorization with Pundit

I want share my experience in the group from our Monday meetup yesterday. Let’s refresh the memory:

“do authorization with pundit gem” – Homework here on github issue #12

https://rubygems.org/gems/pundit

We went to this page and bundle it to our Gemfile

gem 'pundit', '~> 1.0.1'

And open up these links on that page.

Homepage: https://github.com/elabs/pundit

Documentation: http://www.rubydoc.info/gems/pundit/1.0.1

Previously we have done the authorization in this way writing on the products_controller and views/products/

# app/controllers/products_controller.rb
if @product.user == current_user

and then also implemented after that the same feature in this way

# app/models/product.rb
  def user_owns?(u)
    self.user == u
  end

  def user_can_change?(u)
    self.user_owns?(u)
  end

# app/controllers/products_controller.rb
if @product.user_owns?(current_user)

What about pundi

Continue reading →


how to start minitest - Ruby on Rails

From my previous post all the setup’s done for Rails, for minitest and Capybara.

http://www.rubydoc.info/github/jnicklas/capybara
https://github.com/blowmage/minitest-rails
https://github.com/blowmage/minitest-rails-capybara

I read those documentations and start testing, by generating test files, with following rails generate commands:

$ rails generate
Rails:
  #other generators omitted
  integration_test

Minitest:
  minitest:feature
  minitest:install

TestUnit:
  test_unit:controller
  test_unit:integration
  test_unit:model
  test_unit:scaffold

I use these generators, I generate these test classes in which I put test methods. If I memorize all these class names, I will be able to do testing without using generators.

  minitest:feature
    Capybara::Rails::TestCase (test/features directory)

  minitest:install
    ActiveSupport::TestCase (test/test_helper.rb)

Continue reading →