フロント用にサクッとAPIのレスポンスを用意するヘ(^o^)ノ

Mock API response with json-server

github.com

Create sample data with Faker.js

github.com

Sample code

github.com

Setup

$ git clone git@github.com:murajun1978/faker-sample.git
$ cd faker-sample 
$ npm install

Start server

$ npm start faker.js

Getting data

$ curl http://localhost:3000/users
[
  {
    "id": 1,
    "name": "Hayden Larkin"
  },
  {
    "id": 2,
    "name": "Mckayla Feest"
  },
  {
    "id": 3,
    "name": "Rowan Schmeler"
  },
  {
    "id": 4,
    "name": "Cyril Grimes"
  },
  {
    "id": 5,
    "name": "Melisa Cremin"
  },
  {
    "id": 6,
    "name": "Deja Corkery II"
  },
  {
    "id": 7,
    "name": "Rod D'Amore"
  },
  {
    "id": 8,
    "name": "Allan Green"
  },
  {
    "id": 9,
    "name": "Jarrod Schoen II"
  },
  {
    "id": 10,
    "name": "Giuseppe Olson"
  }
]

Faker.js

module.exports = function() {
  var faker = require('faker')

  return {
    users: Array.from(Array(10), (_, i) => {
      return {
        id: i + 1,
        name: faker.name.findName()
      }
    })
  }
}

Happy Hacking٩( ‘ω’ )و

GitbookをGitHub Pagesで公開する ヘ(^o^)ノ

Gitbook

markdownで書ける電子書籍作成ツール

HTMLや電子書籍(PDF,EPUB,MOBI)にoutputできる

今回はHTMLをoutputして、GitHub Pagesのホスティング機能を使って公開してみます

github.com

GitHub Pages

GitHubホスティングサービス

Organization と Project Pages で使うことができる

今回はProject Pagesを使う

Project Pagesを使うにはビルド後のファイルを gh-pages ブランチへpushする必要があります

[コード管理用] https://github.com/username/projectname

[GitHub Pages] https://username.github.io/projectname

Custom domainも使えるよ

Using a custom domain with GitHub Pages - User Documentation

pages.github.com

CircleCI

GitHubなどと連携して自動でビルドやテストしてくれる

CircleCIを使ってmasterにpushされたら自動でビルドを実行し、 gh-pages ブランチへpushする

circleci.com

ご注意

CircleCIの秘密鍵read-only なのでpushできない

なので、 read/write な権限をもってる秘密鍵を登録する必要がある

参考

GitHub Managing deploy keys | GitHub Developer Guide

CircleCI Adding read/write deployment key - CircleCI

Package

gh-pages ブランチへpushする為に使ったパッケージ

べんりすっね

www.npmjs.com

Gitbook Boilerplate

なんか最近よくみるので作ってみました

ボイラープレートとかちょっとかっこいい( ˘ω˘)

github.com

使い方

ローカルにclone

$ git clone git@github.com:murajun1978/gitbook-boilerplate.git gitbook-sample

$ cd gitbook-sample

$ rm -rf .git

Gitbookのセットアップ

$ npm install

$ npm run init

リポジトリにpush

$ git init

$ git add .

$ git commit -m "Initial commit"

$ git remote add origin [remote URL]

$ git push -u origin master

CircleCIの環境変数をセット

Project settings > Environment Variables

https://circleci.com/gh/[username]/[project-name]/edit#env-vars

name: USERNAME
value: [username]

name: EMAIL
value: [email]

CircleCIでbuildを実行

Happy Hacking٩( ‘ω’ )و

RailsのPolymorphicでhas_oneするヘ(^o^)ノ

Polymorphicのhas_one関連を書いてる記事が少なかったので

ついでにPolymorphicのおさらいしておく

環境

モデルをgeneratorでつくる

# zshなんでエスケープしてますです
$ bin/rails g model picture imageable:references\{polymorphic\}
$ bin/rake db:migrate
class Picture < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true
end

できました

has_many

まずは has_manyから

関連モデルをgeneratorでつくる

$ bin/rails g model employee name
$ bin/rake db:migrate

モデルにhas_manyを設定

class Employee < ActiveRecord::Base
  has_many :pictures, as: :imageable
end

コンソールで確認してみる

$ bin/rails c -s
> employee.imageable.create
=> #<Employee id: 1, name: nil, created_at: "2016-04-23 15:51:52", updated_at: "2016-04-23 15:51:52">
> employee.pictures.create
=> #<Picture id: 1, imageable_id: 1, imageable_type: "Employee", created_at: "2016-04-23 15:52:17", updated_at: "2016-04-23 15:52:17">

できました

has_one

さて、問題のhas_one

関連モデルをgeneratorでつくる

$ bin/rails g model product name
$ bin/rake db:migrate

モデルにhas_oneを設定

class Product < ActiveRecord::Base
  has_one :picture, as: :imageable
end

コンソールで確認してみる

$ bin/rails c -s
> product = Product.create
=> #<Product id: 1, name: nil, created_at: "2016-04-23 15:58:33", updated_at: "2016-04-23 15:58:33">
> product.picture.create
NoMethodError: undefined method `create' for nil:NilClass

怒られました

> product.create_picture
=> #<Picture id: 1, imageable_id: 1, imageable_type: "Product", created_at: "2016-04-23 16:10:46", updated_at: "2016-04-23 16:10:46">

できました

Polymorphicでhas_oneするケースが少ないかも( ˘ω˘)

そもそも、Polymorphic関係なかったんや、、

Happy Hacking٩( ‘ω’ )و

参考

ActiveRecord::Associations::ClassMethods

Arrayでinjectを使ってみるヘ(^o^)ノ

injectはとても便利( ˘ω˘)

[1, 2, 3].inject(:+)  #=> 6

こんな感じで読みやすくていい感じ

total_price = 90
total_price += [10, 20].inject(:+)  #=> 120

Railsのバリデーションとかで使うならこんな感じかな

# 以下の値を仮定
limit_total_price = 100
total_price = 100

if items.map(&:price).inject(total_price, :+)  > limit_total_price
  errors.add(:total_price, "over the limit")
end

# with ActiveSupport
if items.map(&:price).sum > limit_total_price
  errors.add(:total_price, "over the limit")
end

Happy Hacking٩( ‘ω’ )و

追記

  • 2015/07/25 JunichiItoさんのコメ反映♪ Thanks!

TempingでMixinするmoduleのテストをしてみる٩( ‘ω’ )و

RailsでモデルにMixinするモジュールをテストしたいとき、みなさんどうしてますか?

mock_model? stub_model? 自分のダミーテーブル作る? 各モデルでテストする?

どれも意外と面倒くさい

そんなときはTempingを使うと楽ちん

ActiveSupport::Concernのモジュールをテストしてみましょう

# app/modules/logical_delete_scopes.rb
module LogicalDeleteScopes
  extend ActiveSupport::Concern
  included do
    scope :without_deleted, -> { where(deleted_at: nil) }
    scope :only_deleted,    -> { where.not(deleted_at: nil) }
  end
end

ダミーのモデルを作る

# spec/support/dummy_model.rb
Temping.create :dummy_model do
  include LogicalDeleteScopes
  with_columns do |t|
    t.datetime :deleted_at
  end
end

テストコードを書く

# spec/modules/logical_delete_scopes_spec.rb
require 'rails_helper'
RSpec.describe LogicalDeleteScopes do
  let!(:enable_data)  { DummyModel.create(deleted_at: nil) }
  let!(:deleted_data) { DummyModel.create(deleted_at: DateTime.now) }

  example do
    expect(DummyModel.without_deleted).to match_array [ enable_data ]
    expect(DummyModel.only_deleted).to match_array [ deleted_data ]
  end
end

Tempingはtemporary tableを使ってるので物理テーブルにも残らない github.com

Happy Hacking٩( ‘ω’ )و

masterのBug Fixだけをreleaseブランチへマージする٩( ‘ω’ )و

GitHubにはrelease機能があります

Creating Releases - User Documentation

masterブランチにマージしてタグ付けてきたが、railsのブランチを見るとリリースブランチが存在します

f:id:murajun1978:20150417005931p:plain

いまさらですが、releaseブランチを作るGitLab Flowを導入しました ( ̄▽ ̄;)

そうするとmasterブランチの変更をreleaseブランチにマージしないとイケない時があります

例えば、Bug FixやSecurity Fixなどなど

では、masterブランチの特定commitだけmergeしてみよう

マージしたいcommitのidを確認する

$ git checkout master
$ git log --oneline
602b23d  bug fix / filter conditions
657c50a  remove duplicates
...

602b23dだけを1-0-stableにマージするときはgit cherry-pickを使います

$ git checkout 1-0-stable
$ git cherry-pick 602b23d

これで特定のcommitだけmergeできました

Happy Hacking٩( ‘ω’ )و

d(゚Д゚ )☆スペシャルサンクス☆( ゚Д゚)b

postd.cc