tag:blog.kangkyu.com,2014:/feedKang-Kyu Lee2020-11-01T01:09:09-07:00Kang-Kyu Leehttp://blog.kangkyu.comSvbtle.comtag:blog.kangkyu.com,2014:Post/export-csv-by-rails2020-11-01T01:09:09-07:002020-11-01T01:09:09-07:00export CSV by rails<p>I will not save a file, just make it downloaded by <code class="prettyprint">Tempfile</code>.<br>
I will not use database table, of course.</p>
<p>This is how my form looks (in <code class="prettyprint">new</code> page)<br>
<code class="prettyprint">config/routes.rb</code> file</p>
<pre><code class="prettyprint lang-rb">resources :accounts, only: [:new, :create]
</code></pre>
<p><code class="prettyprint">app/views/accounts/new.html.erb</code> file</p>
<pre><code class="prettyprint"><%= 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 %>
</code></pre>
<p>When the form is submitted, it triggers <code class="prettyprint">create</code> action. Form submit of <code class="prettyprint">form_with</code> makes POST request to <code class="prettyprint">accounts_path</code> with parameters. And rails syntax <code class="prettyprint">resources :accounts</code> makes <code class="prettyprint">create</code> action of accounts controller triggered by that POST request.</p>
<p>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 <code class="prettyprint">@account</code> in the form) in this case, because we are not going to save anything.</p>
<p><code class="prettyprint">app/controllers/accounts_controller.rb</code> file</p>
<pre><code class="prettyprint">class AccountsController < ApplicationController
def create
# ...
end
end
</code></pre>
<p>At this point <code class="prettyprint">params[:names]</code> is available in <code class="prettyprint">create</code> method. (we call it an ‘action’ because it’s a method in a rails controller) So, we can use user input from the form here.</p>
<p>This is for instagram accounts. I wanted to show this code because this tool does not work. So do not use it for fetching data from instagram.</p>
<pre><code class="prettyprint lang-rb">def create
headers = ['account_name', 'business_email', 'business']
filename = "business emails #{Date.today}.csv"
Tempfile.open do |tempfile|
CSV.open(tempfile.path, "wb", write_headers: true, headers: headers) do |csv|
params[:names].split("\r\n").each do |account_name|
account_name = account_name.tr(' ', '')
uri = URI("https://www.instagram.com/#{account_name}/?__a=1")
res = Net::HTTP.get_response(uri)
if res.is_a?(Net::HTTPSuccess)
body = JSON(res.body)
business_email = body['graphql']['user']['business_email']
is_business = body['graphql']['user']['is_business_account']
csv << [account_name, business_email, is_business]
end
end
end
send_data File.read(tempfile.path), filename: filename, type: 'text/csv'
end
end
</code></pre>
<p>ruby <code class="prettyprint">Tempfile</code> is used and <code class="prettyprint">CSV</code> is used (you may need <code class="prettyprint">require 'csv'</code> on top of the file). I put everything in the <code class="prettyprint">Tempfile.open</code> block because everything should happen before the tempfile is closed. Other than that, some <code class="prettyprint">net/http</code> code is used.</p>
<p>So now we can generate / export a CSV file without saving a file, without database. Thank you</p>
tag:blog.kangkyu.com,2014:Post/post-12020-01-04T15:45:51-08:002020-01-04T15:45:51-08:00레일스로 코딩 배우기<p>나는 루비가 코딩을 배우기에 좋은 출발점이라고 생각한다<br>
Learn To Program 이라는 책을 읽어보라 <a href="https://pine.fm/LearnToProgram/">https://pine.fm/LearnToProgram/</a></p>
<p>물론 어느 programming language 로 시작하든지 코딩을 배우는 것은 인생에서 매우 중요하다고 생각한다</p>
<p>그리고 루비를 배우기에는 레일스가 좋은 출발점이라고 생각한다<br>
지금 시작해보자</p>
<pre><code class="prettyprint lang-sh">rails new app_name
cd app_name
</code></pre>
<p>레일스의 기본은 scaffolding 이다 (한국말로는 “비계"라고 함) 그러므로 한번 따라가보자</p>
<pre><code class="prettyprint lang-sh">rails generate migration create_cups name size
rails db:migrate
</code></pre>
<p><code class="prettyprint">cups</code> 는 여기서 테이블의 이름이다<br>
테이블은 데이타베이스를 배울 때 나오는 말이다</p>
<p>그리고 </p>
<pre><code class="prettyprint lang-rb">class Cup < ApplicationRecord
end
</code></pre>
<p>이렇게 하고</p>
<pre><code class="prettyprint lang-rb">class CupsController < ApplicationController
def index
@cups = Cup.all
end
end
</code></pre>
<p>이렇게 하고</p>
<pre><code class="prettyprint lang-rb">resources :cups
</code></pre>
<p>이렇게 하고</p>
<pre><code class="prettyprint"><% @cups.each do |cup| %>
<%= cup.name %>
<%= cup.size %>
<% end %>
</code></pre>
<p>이렇게 하면 화면에 컵의 목록을 볼수가 있다<br>
물론 (중요하지 않은) 많은 것을 생략하였다</p>
<p>중요한 것은 <code class="prettyprint">@cups</code> 가 컵의 목록을 가지고 넘어간다는 것이다<br>
그래서 instance variable 이라고 한다</p>
<p>잘 생각해보자<br>
데이타베이스의 테이블이 가지고 있는 컵의 목록이 브라우저 화면으로 나오게 하는 것이 이와 같은 패턴으로 이루어진다는 것을</p>
<p>이것이 레일스의 기본이다</p>
<p>생략한 것 중에서 코드가 들어가는 자리는 다음과 같이 확인할 수 있다<br>
이와 같이 시작해서</p>
<pre><code class="prettyprint lang-sh">rails new app_name
cd app_name
</code></pre>
<p><code class="prettyprint">generate migration create_cups</code> 대신에 <code class="prettyprint">generate scaffold cups</code> 한다</p>
<pre><code class="prettyprint lang-sh">rails generate scaffold cups name size
rails db:migrate
</code></pre>
<p>그리고 나서 다음의 파일을 열어서 코드를 확인해 보자<br>
<code class="prettyprint">app/models/cup.rb</code><br>
<code class="prettyprint">app/controllers/cups_controller.rb</code><br>
<code class="prettyprint">config/routes.rb</code><br>
<code class="prettyprint">app/views/cups/index.html.erb</code></p>
<p>레일스가 좋은 출발점이라고 한 것은 개인적인 생각인데, 다만 적은 루비 코드로 뭔가 쓸모있는 것을 만들어 내는 데서 재미를 느낄 수 있고 또한 차차 적응해 가면서 그 아래에 있는 코드를 이해하고 싶은 생각이 들 수도 있기 때문이다.</p>
<p>그러면 결국 plain Ruby 의 기본을 익히는 단계로 가는데, 거기에는 여러가지 방법이 있지만 그때 나는 Learn To Program 이라는 책을 읽었다 (한국어 번역본도 있음) <a href="https://pine.fm/LearnToProgram/">https://pine.fm/LearnToProgram/</a></p>
<p>그리고 Ruby 와 Ruby on Rails (레일스) 를 설치하는 방법은 찾아보면 얼마든지 있다 예를 들면 <a href="https://www.digitalocean.com/community/tutorials/how-to-install-ruby-on-rails-with-rbenv-on-macos">https://www.digitalocean.com/community/tutorials/how-to-install-ruby-on-rails-with-rbenv-on-macos</a></p>
<p>문의사항은 <a href="mailto:lee@kangkyu.com">lee@kangkyu.com</a> 으로 </p>
tag:blog.kangkyu.com,2014:Post/i-wrote-merge-sort-in-ruby2018-04-13T23:11:45-07:002018-04-13T23:11:45-07:00I wrote merge sort in Ruby<p>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.) </p>
<p>I thought I should try to write it in Ruby.</p>
<p>The steps of the merge sort are:</p>
<ul>
<li>First, split the array (yes, I’m sorting an array of numbers) into two halves.</li>
<li>Second, sort those two arrays.</li>
<li>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) </li>
</ul>
<p>As always, I am writing a test first (lol) because I like to see some tests are passing.</p>
<pre><code class="prettyprint lang-rb">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
</code></pre>
<p>I am going to name the two sorted arrays as <code class="prettyprint">left</code> and <code class="prettyprint">right</code></p>
<pre><code class="prettyprint lang-rb">class Sorter
def self.merge_sort(array)
left = array[0..mid]
right = array[mid + 1..-1]
# not done yet
end
end
</code></pre>
<p>What is <code class="prettyprint">mid</code>? It is index of an element which is in the middle. In my case, I include this element to the <code class="prettyprint">left</code> array. </p>
<pre><code class="prettyprint lang-rb">class Sorter
def self.merge_sort(array)
mid = (array.size - 1) / 2
# when array has 3 elements, mid index is 1
left = array[0..mid]
# then this one becomes array[0..1] (2 elements)
right = array[mid + 1..-1]
# this one becomes array[2..-1] (1 element)
# ...
end
end
</code></pre>
<p>Let’s not forget these two arrays (<code class="prettyprint">left</code> and <code class="prettyprint">right</code>) are magically sorted. And do not worry because there will be magical “recursion”. </p>
<p>And then, pick the smallest number from the two arrays. Here, we already know the smallest number of each array. (duh, they are sorted)</p>
<p>Now I can compare the leftmost element of <code class="prettyprint">left</code> array and the leftmost element of <code class="prettyprint">right</code> array, and update original array with smaller one, one by one.</p>
<pre><code class="prettyprint lang-rb">class Sorter
def self.merge_sort(array)
mid = (array.size - 1) / 2
left = array[0..mid].sort
right = array[mid + 1..-1].sort
array.size.times do |i|
if left[0] < right[0]
array[i] = left.shift
else
array[i] = right.shift
end
end
array
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
</code></pre>
<p>Yay! the test fails with error because there are edge cases! It is because one out of two arrays didn’t have the leftmost element at some point. (in other words, the array was empty)</p>
<p>For example, <code class="prettyprint">left[0]</code> can be <code class="prettyprint">nil</code> when <code class="prettyprint">right[0]</code> is an integer.</p>
<pre><code class="prettyprint lang-sh">ArgumentError: comparison of Integer with nil failed
</code></pre>
<p>This time I change the conditions and loops, to see how things are going.</p>
<pre><code class="prettyprint lang-rb">class Sorter
def self.merge_sort(array)
mid = (array.size - 1) / 2
left = array[0..mid].sort
right = array[mid + 1..-1].sort
i = 0
while left.size > 0 && right.size > 0
if left[0] < right[0]
array[i] = left.shift
i += 1
else
array[i] = right.shift
i += 1
end
end
while left.size > 0
array[i] = left.shift
i += 1
end
while right.size > 0
array[i] = right.shift
i += 1
end
array
end
end
</code></pre>
<p>Now test shall pass! By the way, I am not supposed to use <code class="prettyprint">sort</code> method in the <code class="prettyprint">merge_sort</code> method to be honest. So let’s now use recursion and complete the code. But look, don’t forget the base condition.</p>
<pre><code class="prettyprint lang-rb">class Sorter
def self.merge_sort(array)
return array if array.size == 1
mid = (array.size - 1) / 2
left = merge_sort(array[0..mid])
right = merge_sort(array[mid + 1..-1])
i = 0
while left.size > 0 && right.size > 0
if left[0] < right[0]
array[i] = left.shift
i += 1
else
array[i] = right.shift
i += 1
end
end
while left.size > 0
array[i] = left.shift
i += 1
end
while right.size > 0
array[i] = right.shift
i += 1
end
array
end
end
</code></pre>
<p>Cool!</p>
tag:blog.kangkyu.com,2014:Post/add-pride-option-to-rake2018-03-21T14:54:00-07:002018-03-21T14:54:00-07:00Add pride option to rake<pre><code class="prettyprint">ruby -Itest test/something_test.rb --pride
</code></pre>
<p>I use <code class="prettyprint">--pride</code> all the time because it gives a rainbow when successful.</p>
<p>but</p>
<pre><code class="prettyprint">rake
</code></pre>
<p>does not have the rainbow. so I found I could add <code class="prettyprint">TESTOPTS</code></p>
<pre><code class="prettyprint">rake TESTOPTS='--pride'
</code></pre>
<p>but I wanted make it as default. After some google search, I went to source code. </p>
<p><a href="https://github.com/ruby/rake/blob/master/lib/rake/testtask.rb">https://github.com/ruby/rake/blob/master/lib/rake/testtask.rb</a></p>
<p>so I opened <code class="prettyprint">Rakefile</code> and added this line.</p>
<pre><code class="prettyprint">t.options = "--pride"
</code></pre>
<p>it works!</p>
<pre><code class="prettyprint lang-rb"># 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
</code></pre>
tag:blog.kangkyu.com,2014:Post/react-with-ruby-on-rails-5-12017-09-13T23:54:17-07:002017-09-13T23:54:17-07:00React with Ruby on Rails 5.1<pre><code class="prettyprint lang-sh">$ 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
</code></pre>
<p>BOTH of two options. why not?</p>
<p><a href="https://yarnpkg.com/en/docs/install#alternatives-tab">https://yarnpkg.com/en/docs/install#alternatives-tab</a></p>
<h2 id="first-let39s-make-api-part_2">First let’s make API part <a class="head_anchor" href="#first-let39s-make-api-part_2">#</a>
</h2>
<p>we need players to render JSON</p>
<pre><code class="prettyprint lang-rb"># db/seeds.rb
movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
</code></pre>
<pre><code class="prettyprint lang-sh">$ rails generate model Movie name:string
$ rails db:migrate
$ rails db:seed
</code></pre>
<p>now <code class="prettyprint">ApplicationController</code> inherits <code class="prettyprint">ActionController::API</code></p>
<pre><code class="prettyprint lang-rb"># app/controllers/movies_controller.rb
class MoviesController < ApplicationController
def index
render json: Movie.all
end
end
</code></pre>
<p>and route</p>
<pre><code class="prettyprint lang-rb"># config/routes.rb
get "/movies", to: 'movies#index'
</code></pre>
<pre><code class="prettyprint lang-sh">$ rails server -p 3001
</code></pre>
<p>on different terminal window,</p>
<pre><code class="prettyprint lang-sh">$ curl 'http://localhost:3001/movies'
[{"id":1,"name":"Star Wars","created_at":"2017-09-15T23:47:07.706Z","updated_at":"2017-09-15T23:47:07.706Z"},{"id":2,"name":"Lord of the Rings","created_at":"2017-09-15T23:47:07.710Z","updated_at":"2017-09-15T23:47:07.710Z"}]
</code></pre>
<p>Looks good.</p>
<h2 id="make-react-page_2">make React page <a class="head_anchor" href="#make-react-page_2">#</a>
</h2>
<p><code class="prettyprint">app/javascript/packs/application.js</code> file says:</p>
<blockquote class="short">
<p>To reference this file, add <%= javascript_pack_tag ‘application’ %> to the appropriate layout file.</p>
</blockquote>
<p>so we need <code class="prettyprint">views</code> directory.. but already did <code class="prettyprint">--api</code></p>
<pre><code class="prettyprint lang-sh">$ rails generate controller home index
</code></pre>
<p>but this has to be changed into this</p>
<pre><code class="prettyprint lang-rb"># app/controllers/home_controller.rb
class HomeController < ApplicationController
def index
end
end
class HomeController < ActionController::Base
def index
end
end
</code></pre>
<p>open <code class="prettyprint">localhost:3001/home/index</code></p>
<p>now we have <code class="prettyprint">ActionController::UnknownFormat</code> error correctly.</p>
<p>make <code class="prettyprint">app/views/home/index.html.erb</code> file</p>
<p>there’s no error</p>
<p>we need this file (a view template) for React</p>
<p>again, <code class="prettyprint">app/javascript/packs/application.js</code> file says:</p>
<blockquote class="short">
<p>To reference this file, add <%= javascript_pack_tag ‘application’ %> to the appropriate layout file.</p>
</blockquote>
<pre><code class="prettyprint lang-sh"># app/views/home/index.html.erb
<%= javascript_pack_tag 'application' %>
</code></pre>
<p>open <code class="prettyprint">localhost:3001/home/index</code> and see</p>
<pre><code class="prettyprint lang-sh">Hello World from Webpacker
</code></pre>
<p>and we have only one this page so make it root:</p>
<p>remove </p>
<pre><code class="prettyprint lang-rb"> get 'home/index'
</code></pre>
<p>add</p>
<pre><code class="prettyprint lang-rb"> root 'home#index'
</code></pre>
<p>now open <code class="prettyprint">localhost:3001/</code> and see</p>
<pre><code class="prettyprint lang-sh">Hello World from Webpacker
</code></pre>
<p>on developer tools console. (type <code class="prettyprint">cmd + option + i</code> and then <code class="prettyprint">Console</code> tab)</p>
<p>it was successful to me.</p>
<h2 id="list-movies_2">List movies <a class="head_anchor" href="#list-movies_2">#</a>
</h2>
<p>I wrote simple <code class="prettyprint">Header</code> and <code class="prettyprint">Movie</code> component. It looks like <code class="prettyprint">componentDidMount</code> does the job.</p>
<pre><code class="prettyprint lang-jsx">// app/javascript/packs/application.js
import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
import createReactClass from 'create-react-class'
var MOVIES = [];
function Header(props) {
return (
<div className="header">
<h1>{props.title}</h1>
</div>
);
}
Header.propTypes = {
title: PropTypes.string.isRequired
}
function Movie(props) {
return (
<div className="movie">
<div className="movie-name">
{props.name}
</div>
</div>
);
}
Movie.propTypes = {
name: PropTypes.string.isRequired
}
var Application = createReactClass({
propTypes: {
title: PropTypes.string
},
getDefaultProps: function() {
return {
title: 'Movie Theater'
};
},
getInitialState: function() {
return {
movies: this.props.initialMovies
};
},
componentDidMount: function() {
var request = new Request('/movies', {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/json'
})
});
fetch(request).then(function(response){
return response.json();
}).then(function(movies){
this.setState({
movies: movies
});
}.bind(this)).catch(function(error){
console.error(error);
});
},
onChange: function(e) {
e.preventDefault();
this.setState({
movie: e.target.value
})
},
render: function() {
return (
<div className="scoreboard">
<Header title={this.props.title} />
<div>
{this.state.movies.map(function (movie, index) {
return (<Movie name={movie.name} key={movie.id} />);
}.bind(this))}
</div>
</div>
);
}
})
</code></pre>
<p>copy following from <code class="prettyprint">app/javascript/packs/hello_react.js</code> file</p>
<pre><code class="prettyprint lang-jsx">document.addEventListener('DOMContentLoaded', () => {
ReactDOM.render(
<Application initialMovies={MOVIES} />,
document.body.appendChild(document.createElement('div')),
)
})
</code></pre>
<p>It’s just working! Next time I’ll do delete or create, update movies.</p>
tag:blog.kangkyu.com,2014:Post/buzzword-bingo-with-rails2017-06-24T22:35:30-07:002017-06-24T22:35:30-07:00buzzword bingo with Rails<p>I ran into “Integrating Elm with Rails 5.1” <a href="https://pragmaticstudio.com/blog/2017/5/12/elm-with-rails-5-1">post</a> on Pragmatic Studio blog a month ago.</p>
<p>And then I wanted to use this Rails setting while watching Pragmatic Studio Elm course. In the video, what is used was <code class="prettyprint">node server.js</code>. I preferred not to understand how it works, so I did the same thing in Rails.</p>
<p>This is what we need at the <a href="https://online.pragmaticstudio.com/courses/elm/modules/16">lesson</a>. It’s not other than just rendering JSON with 5 random buzzword entries in the back-end. For example:</p>
<pre><code class="prettyprint lang-json">[
{
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
}
]
</code></pre>
<p>In <code class="prettyprint">app/controllers/entries_controller.rb</code>, following is what I did. This code is rendering 5 random entries as JSON.</p>
<pre><code class="prettyprint lang-ruby">class EntriesController < ApplicationController
def random_entries
@entries = Entry.order("RANDOM()").limit(5)
end
end
</code></pre>
<p>We need more code, on top of the <a href="https://pragmaticstudio.com/blog/2017/5/12/elm-with-rails-5-1">Integrating Elm with Rails 5.1</a>. We need a route, and a table, as well as a controller.</p>
<p>config/routes.rb</p>
<pre><code class="prettyprint lang-rb"> scope defaults: {format: :json} do
get '/random-entries' => 'entries#random_entries'
end
</code></pre>
<p>generate Entry model</p>
<pre><code class="prettyprint lang-sh">rails generate model Entry phrase:string points:integer
rails db:migrate
</code></pre>
<p>And if you prefer, you can copy and paste this into your <code class="prettyprint">db/seeds.rb</code> file. and run <code class="prettyprint">rails db:seed</code></p>
<pre><code class="prettyprint lang-rb">Entry.create([
{
phrase: "Future-Proof",
points: 100
},
{
phrase: "Doing Agile",
points: 200
},
{
phrase: "In The Cloud",
points: 300
},
{
phrase: "Rock-Star Ninja",
points: 400
},
{
phrase: "Best of Breed",
points: 150
},
{
phrase: "Reactive",
points: 250
},
{
phrase: "Zero to Hero",
points: 350
},
{
phrase: "User-Centric",
points: 175
},
{
phrase: "Cross-Platform",
points: 225
},
{
phrase: "Synergize",
points: 375
},
])
</code></pre>
<p>Of course, you’re using Rails 5.1 – and you have read the great post on Pragmatic Studio blog, and taking their Building Web Apps with Elm <a href="https://pragmaticstudio.com/courses/elm">course</a>.</p>
<p>Ah, don’t forget. Elm code should be changed accordingly. Let us change <code class="prettyprint">getEntries</code> command on <code class="prettyprint">app/javascript/packs/Bingo.elm</code> file.</p>
<pre><code class="prettyprint lang-elm">getEntries : Cmd Msg
getEntries =
Http.send NewEntries (Http.get "/random-entries" (Decode.list entryDecoder))
</code></pre>
<p>… because it’s not a separate server (as like <code class="prettyprint">http://localhost:3000/random-entries</code>) any more. I deployed with Heroku, and it was a very simple process.</p>
tag:blog.kangkyu.com,2014:Post/ri2016-07-11T05:22:11-07:002016-07-11T05:22:11-07:00ri<p>Doc Rdoc ..</p>
<p><a href="https://www.omniref.com/ruby/gems/httparty/0.13.1/symbols/HTTParty::ClassMethods/default_params">https://www.omniref.com/ruby/gems/httparty/0.13.1/symbols/HTTParty::ClassMethods/default_params</a></p>
<p><a href="http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest/Assertions.html#method-i-assert_equal">http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest/Assertions.html#method-i-assert_equal</a></p>
<p><a href="http://www.rubydoc.info/gems/minitest/5.8.3/Minitest/Assertions#assert_equal-instance_method">http://www.rubydoc.info/gems/minitest/5.8.3/Minitest/Assertions#assert_equal-instance_method</a></p>
<pre><code class="prettyprint lang-shell">ri Array#each
</code></pre>
<p>If you have still this in <code class="prettyprint">~/.gemrc</code> file (still works)</p>
<pre><code class="prettyprint lang-shell">gem: --no-ri --no-rdoc
</code></pre>
<p>Change it into</p>
<pre><code class="prettyprint lang-shell"># ~/.gemrc
install: --no-document
update: --no-document
gem: --no-document
</code></pre>
<p>because we have this new flag, and the old <code class="prettyprint">--no-ri</code> flag has been deprecated.</p>
<pre><code class="prettyprint lang-shell">--[no-]document [TYPES] - Generate documentation for installed gems List the documentation types you wish to generate. For example: rdoc,ri
</code></pre>
<p>However if you have it this way, you can have ri command for all gems with you.</p>
<pre><code class="prettyprint">--document ri
--no-document rdoc
</code></pre>
<p><a href="http://ruby-doc.org/">http://ruby-doc.org/</a><br>
<a href="http://www.rubydoc.info/">http://www.rubydoc.info/</a></p>
<p>To update, I found ri command useful <a href="http://www.jstorimer.com/blogs/workingwithcode/7766081-5-reasons-you-should-use-ri-to-read-ruby-documentation">http://www.jstorimer.com/blogs/workingwithcode/7766081-5-reasons-you-should-use-ri-to-read-ruby-documentation</a></p>
<p>all std-lib or core-ruby are already there. And for any gem, you can always download ri documentation to you then remove it. use <code class="prettyprint">gem rdoc</code></p>
<pre><code class="prettyprint lang-shell">gem rdoc minitest --ri
ri Minitest::Assertions.assert_equal
gem rdoc httparty --no-ri --overwrite
</code></pre>
<p>or when you install</p>
<pre><code class="prettyprint lang-shell">$ gem install httparty --document ri
$ ri default_params
</code></pre>
tag:blog.kangkyu.com,2014:Post/try-blocks2016-05-08T15:40:41-07:002016-05-08T15:40:41-07:00Try blocks<h1 id="try-block_1">try Block <a class="head_anchor" href="#try-block_1">#</a>
</h1>
<p>…hitting the wall? then stop learnng Ruby, and come back any time. This is how I learned Ruby coding.</p>
<p>I started with Chris Pine <a href="https://pine.fm/LearnToProgram/">book</a>, which starts with <code class="prettyprint">puts</code> in <strong>Chapter 2</strong>. (<code class="prettyprint">'Hello World'</code> shows in the <strong>Introduction</strong>, but that’s not where I started) So that’s why my first Ruby code was:</p>
<pre><code class="prettyprint lang-rb">puts 1+2
# 3
# => nil
</code></pre>
<p>and so on. Nobody quits at this point.</p>
<pre><code class="prettyprint lang-rb">v = 1+2
puts v
# 3
# => nil
</code></pre>
<p>variable, parameter, argument, object… and block.</p>
<pre><code class="prettyprint lang-rb">{ puts 1+2 }
</code></pre>
<p>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)</p>
<pre><code class="prettyprint lang-rb">def say
puts 1+2
end
say
# 3
# => nil
</code></pre>
<p>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.</p>
<pre><code class="prettyprint lang-rb">def say(a, b)
puts a+b
end
say(1, 2)
# 3
# => nil
</code></pre>
<p>Likewise, it would look nicer if you can call it with a block.</p>
<pre><code class="prettyprint lang-rb">def say
yield
end
say { puts 1+2 }
# 3
# => nil
</code></pre>
<p>After a while, I’ve been seeing things like this. Here <code class="prettyprint">say</code> doesn’t do anything but “yield” for simplicity in this working code. (<code class="prettyprint">yield</code> means “somewhere” - you really know what <code class="prettyprint">yield</code> is, because it’s right in the middle of every Rails app.) And in this case, <code class="prettyprint">{}</code> is a block.</p>
<pre><code class="prettyprint lang-rb">b = { puts 1+2 }
say b
# you wish
</code></pre>
<p>I wanted to do something like this. But it didn’t work.</p>
<p>First of all, it is something different. They say you omit parentheses when you can.</p>
<pre><code class="prettyprint lang-rb">puts(1+2)
# 3
# => nil
say({ puts 1+2 })
# SyntaxError: (irb):1: syntax error, unexpected tINTEGER, expecting keyword_do or '{' or '('
# say({ puts 1+2 })
# ^
# (irb):1: syntax error, unexpected '}', expecting end-of-input
# say({ puts 1+2 })
# ^
# from /Users/klee/.rbenv/versions/2.3.0/bin/irb:11:in `<main>'
say { puts 1+2 }
# 3
# => nil
</code></pre>
<p>And you don’t “save” it into a variable, either.</p>
<pre><code class="prettyprint lang-rb">v = 1+2
# => 3
b = { puts 1+2 }
# SyntaxError: (irb):1: syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
# b = { puts 1+2 }
# ^
# (irb):1: syntax error, unexpected '}', expecting end-of-input
# from /Users/klee/.rbenv/versions/2.3.0/bin/irb:11:in `<main>'
</code></pre>
<p>Errors are only bad words. You don’t read error messages, if you’re beginning. Because it’s humiliating!</p>
<p>I google.</p>
<p>I found <code class="prettyprint">-> {}</code> (stab).</p>
<pre><code class="prettyprint lang-rb">b = -> { puts 1+2 }
# => #<Proc:0x007f951aa38bd8@(irb):1 (lambda)>
</code></pre>
<p>And it’s working! No error!</p>
<p>It might have been saved. Used it.</p>
<pre><code class="prettyprint lang-rb">b = -> { puts 1+2 }
say b
# ArgumentError: wrong number of arguments (given 1, expected 0)
# from (irb):4:in `say'
# from (irb):10
# from /Users/klee/.rbenv/versions/2.3.0/bin/irb:11:in `<main>'
</code></pre>
<p>Not working. So I need read more of it when google.</p>
<pre><code class="prettyprint lang-rb">b.call
# 3
# => nil
</code></pre>
<h1 id="block-or-proc_1">block or proc <a class="head_anchor" href="#block-or-proc_1">#</a>
</h1>
<p>I remembered <code class="prettyprint">yield</code> is in other words <code class="prettyprint">block.call</code> from Chris Pine book. He actually prefers <code class="prettyprint">block.call</code> over <code class="prettyprint">yield</code> in Chapter 14. (I remembered that. That’s what I could do. Amazing because I forgot everything else on that Chapter)</p>
<pre><code class="prettyprint lang-rb">def say &b
b.call
end
say { puts 1+2 }
# 3
# => nil
b = -> { puts 1+2 }
say &b
# 3
# => nil
</code></pre>
<p>What is Ampersand(Et) doing here?</p>
<pre><code class="prettyprint lang-rb">&b
# SyntaxError: (irb):17: syntax error, unexpected &
# from /Users/klee/.rbenv/versions/2.3.0/bin/irb:11:in `<main>'
</code></pre>
<pre><code class="prettyprint lang-rb">say(&b)
# 3
# => nil
say(&-> { puts 1+2 })
# 3
# => nil
say { puts 1+2 }
# 3
# => nil
-> { puts 1+2 }.call
# 3
# => nil
</code></pre>
<p>Okay.. so you get the idea. First do <code class="prettyprint">-></code>, and then do <code class="prettyprint">&</code>. It’s “saved” and then “passed” somehow.</p>
<p>I wanted to say 3 three times.</p>
<pre><code class="prettyprint lang-rb">def say
yield
yield
yield
end
say { puts 1+2 }
# 3
# 3
# 3
# => nil
</code></pre>
<pre><code class="prettyprint lang-rb">3.times { puts 1+2 }
b = -> { puts 1+2 }
3.times &b
# ArgumentError: wrong number of arguments (given 1, expected 0)
# from (irb):13:in `block in irb_binding'
# from (irb):14:in `times'
# from (irb):14
# from /Users/klee/.rbenv/versions/2.3.0/bin/irb:11:in `<main>'
</code></pre>
<h1 id="why_1">Why? <a class="head_anchor" href="#why_1">#</a>
</h1>
<p>which is an object? You know what <strong>object</strong> is? If you know, then you know everything in Ruby. “Everything is an object in Ruby” you always hear.</p>
<p>You can tell it’s an object, whenever it doesn’t give any syntax error. Type a thing and press enter on <code class="prettyprint">irb</code>, if you see an error then it’s not a thing.</p>
<pre><code class="prettyprint lang-rb">{ puts 1+2 } # not an object
-> { puts 1+2 } # object (and it's a "Proc" object)
b = -> { puts 1+2 }
&-> { puts 1+2 } # not an object
&b
</code></pre>
<pre><code class="prettyprint lang-rb"># when doing something, it should be a block
say { puts 1+2 }
# when storing, it should be an object (it should be a proc)
b = -> { puts 1+2 }
b.call
</code></pre>
<h1 id="again-why_1">Again, why? <a class="head_anchor" href="#again-why_1">#</a>
</h1>
<pre><code class="prettyprint lang-rb">-> { puts 1+2 }
# => #<Proc:0x007fdd5aa2a6e0@(irb):15 (lambda)>
proc { puts 1+2 }
# => #<Proc:0x007fdd5aa19f70@(irb):16>
</code></pre>
<p>Stab is not all. “Go look at the documentation.” (that’s what you always hear, too. And I don’t want to listen, because 9 out of 10 it’s hard to read.)</p>
<blockquote class="short">
<p>::new is the same as proc.</p>
<p><a href="http://ruby-doc.org/core-2.3.0/Proc.html">http://ruby-doc.org/core-2.3.0/Proc.html</a></p>
</blockquote>
<p>You can use <code class="prettyprint">Proc.new {}</code> instead of <code class="prettyprint">proc {}</code> here.</p>
<pre><code class="prettyprint lang-rb">Proc.new {}
# => #<Proc:0x007f951a97aea8@(irb):21>
proc {}
# => #<Proc:0x007f951a96a260@(irb):22>
</code></pre>
<p>These two do the same thing too.</p>
<pre><code class="prettyprint lang-rb">lambda {}
# => #<Proc:0x007f951a961cf0@(irb):23 (lambda)>
-> {}
# => #<Proc:0x007f951a9599d8@(irb):24 (lambda)>
</code></pre>
<p>And</p>
<pre><code class="prettyprint lang-rb">b = proc { puts 1+2 }
3.times &b
# 3
# 3
# 3
# => 3
</code></pre>
<p>Is working!</p>
<p>But why? I like the “stabby lambda”!</p>
<p><code class="prettyprint">Integer#times</code> has this description.</p>
<blockquote>
<p>Iterates the given block int times, passing in values from zero to int - 1.</p>
<pre><code class="prettyprint lang-rb"> 5.times do |i|
print i, " "
end
#=> 0 1 2 3 4
</code></pre>
<p><a href="http://ruby-doc.org/core-2.3.0/Integer.html#method-i-times">http://ruby-doc.org/core-2.3.0/Integer.html#method-i-times</a></p>
</blockquote>
<p>So the secret was two pipes (vertical bars).</p>
<pre><code class="prettyprint lang-rb">b = -> { |i| puts 1+2 }
# SyntaxError: (irb):3: syntax error, unexpected '|'
# b = -> { |i| puts 1+2 }
# ^
# (irb):3: syntax error, unexpected tINTEGER, expecting keyword_do or '{' or '('
# b = -> { |i| puts 1+2 }
# ^
# from /Users/ugp/.rbenv/versions/2.2.4/bin/irb:11:in `<main>'
</code></pre>
<p>Oops, it’s not working.. so after search,</p>
<pre><code class="prettyprint">b = ->(i) { puts 1+2 }
# => #<Proc:0x007faa29879b20@(irb):5 (lambda)>
3.times &b
# 3
# 3
# 3
# => 3
</code></pre>
<p>This one also working, you can have “lambda lambda”</p>
<pre><code class="prettyprint">b = lambda {|i| puts 1+2 }
# => #<Proc:0x007faa298621a0@(irb):7 (lambda)>
3.times &b
# 3
# 3
# 3
# => 3
</code></pre>
<p>Again, why?</p>
<pre><code class="prettyprint lang-rb">b = -> { puts 1+2 }
3.times &b
# ArgumentError: wrong number of arguments (given 1, expected 0)
</code></pre>
<p>Now you read errors. It says wrong number of arguments.</p>
<blockquote class="short">
<p>Returns true for a Proc object for which argument handling is rigid. Such procs are typically generated by lambda.</p>
<p><a href="http://ruby-doc.org/core-2.3.0/Proc.html#method-i-lambda-3F">http://ruby-doc.org/core-2.3.0/Proc.html#method-i-lambda-3F</a></p>
</blockquote>
<p>Therefore, block parameters are <strong>necessary</strong> for a lambda. Not for a proc.</p>
<h1 id="summary_1">Summary <a class="head_anchor" href="#summary_1">#</a>
</h1>
<ul>
<li>block is not an object <code class="prettyprint">{ puts 1+2 }</code>, only “chunk of code”</li>
<li>proc is an object
<ul>
<li>lambda: <code class="prettyprint">-> { puts 1+2 }</code>
</li>
<li>proc: <code class="prettyprint">proc { puts 1+2 }</code>
</li>
</ul>
</li>
<li>when a proc is a lambda, it’s sensitive to arguments.</li>
</ul>
<h1 id="the-end_1">The end <a class="head_anchor" href="#the-end_1">#</a>
</h1>
<p>Cases with block parameters, block arguments.. for another day.</p>
tag:blog.kangkyu.com,2014:Post/postgresql-for-rails-on-apple-os-x2015-08-11T14:10:06-07:002015-08-11T14:10:06-07:00PostgreSQL for Rails on Apple OS X<p>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 <a href="http://www.meetup.com/laruby/">Rails Meetup</a> Study Group.</p>
<hr>
<p>I’ve done it on Apple machine, so started with following (Just in case, starting this with brew updating)</p>
<pre><code class="prettyprint">brew update && brew upgrade
brew install postgres
</code></pre>
<p>Of course it should be done after you <a href="https://github.com/Homebrew/homebrew/blob/master/share/doc/homebrew/Installation.md">install homebrew</a> package manager first if not done yet, and for me I simply followed their easiest way on <a href="http://brew.sh/">brew.sh</a> page.</p>
<pre><code class="prettyprint">ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
</code></pre>
<hr>
<p>Check if following <code class="prettyprint">psql</code> command working. (you will see your username of the machine in place of <code class="prettyprint">your_username</code>, and more lines omitted here.)</p>
<pre><code class="prettyprint">$ psql --help
psql is the PostgreSQL interactive terminal.
General options:
-d, --dbname=DBNAME database name to connect to (default: "your_username")
Connection options:
-h, --host=HOSTNAME database server host or socket directory (default: "local socket")
-p, --port=PORT database server port (default: "5432")
-U, --username=USERNAME database user name (default: "your_username")
-w, --no-password never prompt for password
-W, --password force password prompt (should happen automatically)
</code></pre>
<p>That means for example, when you type simply this command:</p>
<pre><code class="prettyprint">psql
</code></pre>
<p>without any options like <code class="prettyprint">-d some_dbname</code> or <code class="prettyprint">--dbname=some_dbname</code>, then it considers your command as something like following:</p>
<pre><code class="prettyprint">psql -U your_username -d your_username
</code></pre>
<p>However, because it said <a href="http://www.postgresql.org/docs/9.3/static/manage-ag-createdb.html">“The first database is always created by the initdb command when the data storage area is initialized. This database is called postgres.”</a> on the documentation, so I did</p>
<pre><code class="prettyprint">psql -d postgres
</code></pre>
<p>…and got an error. This error was given because I didn’t do <strong>create the first database by the initdb command</strong>. I followed another page of documentation: <a href="http://www.postgresql.org/docs/9.3/static/creating-cluster.html">“There is no default, although locations such as <code class="prettyprint">/usr/local/pgsql/data</code> or <code class="prettyprint">/var/lib/pgsql/data</code> are popular.”</a></p>
<pre><code class="prettyprint">$ initdb -D /usr/local/pgsql/data
</code></pre>
<p>Done. </p>
<pre><code class="prettyprint">$ psql -d postgres
\psql (9.4.4)
Type "help" for help.
postgres=#
</code></pre>
<p>Now this should be working (exit with <code class="prettyprint">\q</code> by the way. for all other backslash commands, check <a href="http://www.postgresql.org/docs/9.3/static/app-psql.html">here</a>) <strong>while database running</strong>.</p>
<hr>
<p>Always don’t forget the database must be up and running to use it. For starting postgres, generally you do</p>
<pre><code class="prettyprint">postgres -D /usr/local/pgsql/data
</code></pre>
<p>But again, I’ve done it on Apple machine, I consider you may <code class="prettyprint">brew services start</code> after you <a href="https://github.com/Homebrew/homebrew-services">install homebrew services</a> because it’s very simple. </p>
<pre><code class="prettyprint">brew tap homebrew/services
</code></pre>
<p>and then</p>
<pre><code class="prettyprint">brew services start postgresql
brew services list
</code></pre>
<p>Now all done, and let’s start with <code class="prettyprint">rails new</code> command with <code class="prettyprint">--database</code> option!</p>
<pre><code class="prettyprint">rails new app_name -d postgresql
</code></pre>
<hr>
<p>If it’s already in the middle of working with <code class="prettyprint">sqlite3</code> gem in your Gemfile, you may change it from something like this</p>
<pre><code class="prettyprint lang-rb">group :development, :test do
gem 'sqlite3'
end
</code></pre>
<p>into this</p>
<pre><code class="prettyprint lang-rb">group :development, :test do
gem 'pg'
end
</code></pre>
<p>And edit <code class="prettyprint">config/database.yml</code> file from something like</p>
<pre><code class="prettyprint lang-rb">default: &default
adapter: sqlite3
pool: 5
timeout: 5000
development:
<<: *default
database: db/development.sqlite3
</code></pre>
<p>into something like</p>
<pre><code class="prettyprint">default: &default
adapter: postgresql
encoding: unicode
pool: 5
development:
<<: *default
database: app_name_development
</code></pre>
<p>or you may config username and password to access the database:</p>
<pre><code class="prettyprint">development:
adapter: postgresql
encoding: unicode
database: app_name_development
pool: 5
username: your_username
password:
</code></pre>
<p>By the way your your_username is not necessary here. Because we mentioned psql command has –username=your_username (Mac user name) by default. (You can always set the <code class="prettyprint">username</code> and <code class="prettyprint">password</code> up differently, but I don’t think it necessary in development.) </p>
<hr>
<p>Databases named <code class="prettyprint">app_name_development</code> or <code class="prettyprint">app_name_test</code> should be created by </p>
<pre><code class="prettyprint">rake db:create
</code></pre>
<p>And then, go back to normal Rails development and test, maybe with</p>
<pre><code class="prettyprint">rake db:migration
</code></pre>
<p>and so on. They say you should use <code class="prettyprint">pg</code> gem because it’s the same one with default database of <strong>heroku</strong>. Maybe that might be why you are going to do this.</p>
<h4 id="interesting-links_4">Interesting links: <a class="head_anchor" href="#interesting-links_4">#</a>
</h4>
<ul>
<li><a href="https://robots.thoughtbot.com/starting-and-stopping-background-services-with-homebrew">https://robots.thoughtbot.com/starting-and-stopping-background-services-with-homebrew</a></li>
<li><a href="https://www.digitalocean.com/community/tutorials/how-to-use-roles-and-manage-grant-permissions-in-postgresql-on-a-vps--2">https://www.digitalocean.com/community/tutorials/how-to-use-roles-and-manage-grant-permissions-in-postgresql-on-a-vps–2</a></li>
</ul>
tag:blog.kangkyu.com,2014:Post/exercismio-with-guardshell2015-08-04T11:33:43-07:002015-08-04T11:33:43-07:00exercism.io with Guard-Shell<p>I’m enjoying <a href="http://help.exercism.io/getting-started-with-ruby.html">exercism.io</a> like anybody else. Inspired by <a href="http://hdnrnzk.me/2012/03/23/ruby-koans-with-guard-shell/">Ruby Koans with guard shell</a> I set it up for my practicing.</p>
<p>Please comment at my <a href="https://gist.github.com/kangkyu/17b014143d7d2afaf2cb">gist</a> for any further suggestions.</p>
<p>In the <code class="prettyprint">~/exercism/ruby</code> directory, add two files <strong>Guardfile</strong> and <strong>Rakefile</strong> after install the guard-shell gem.</p>
<h3 id="terminal_3">Terminal <a class="head_anchor" href="#terminal_3">#</a>
</h3>
<pre><code class="prettyprint lang-sh">gem install guard guard-shell
guard init shell
</code></pre>
<h3 id="guardfile_3">Guardfile <a class="head_anchor" href="#guardfile_3">#</a>
</h3>
<pre><code class="prettyprint lang-rb">guard :shell do
watch(/^(.+)\.rb$/) do |m|
`rake test TEST="#{m[1].chomp('_test')}_test.rb" TESTOPTS="--pride"`
end
end
</code></pre>
<p>I added <strong>pride</strong> option because it colors a rainbow when success!</p>
<h3 id="rakefile_3">Rakefile <a class="head_anchor" href="#rakefile_3">#</a>
</h3>
<pre><code class="prettyprint lang-rb">#!/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
</code></pre>
<pre><code class="prettyprint">$ guard
</code></pre>
<p>And then run <code class="prettyprint">guard</code> on <code class="prettyprint">~/exercism/ruby</code> directory prompt. Now whenever I make changes onto the exercise files in any directory <code class="prettyprint">~/exercism/ruby/name-of-exercise</code>, it triggers testing automatically.</p>
<p>Again, please comment at my Github <a href="https://gist.github.com/kangkyu/17b014143d7d2afaf2cb">gist</a>. Thank you!</p>