Destructuring Object in ES6

often use

const props = {
  label: 'label',
  text: 'text'
}

const { label, text } = props

console.log(label) #=> 'label'
console.log(text) #=> 'text'

default value

const props = {
  label: 'label'
}

const { label, text = 'text' } = props

console.log(label) #=> 'label'
console.log(text) #=> 'text'

alias

const props = {
  label: 'label',
  text: 'text'
}

const { label: l, text: t } = props

console.log(l) #=> 'label'
console.log(t) #=> 'text'

others

const props = {
  label: 'label',
  text: 'text',
  required: true,
  visible: true
}

const { label, text, options } = props

console.log(label) #=> 'label'
console.log(text) #=> 'text'
console.log(options) #=> {required: true, visible: true}

Happy Hacking٩( ‘ω’ )و

Jestでcontextを使うヘ(^o^)ノ

Environment

Jest 18.1.0

Jestでは context が使えません、、

github.com

なので、使えるようにしてみましょう。

とはいっても、contextはdescribeのエイリアスです。

global変数を定義してみましょうヘ(^o^)ノ

// setupTestFramework.js
global.context = describe

このsetupファイルをテストを実行前にloadします

// package.json
"jest": {
  "setupTestFrameworkScriptFile": "./setupTestFramework"
}
// App.spec.js
import React from 'react'
import renderer from 'react-test-renderer'

import App from '../../client/components/App'

describe('<App />', () => {
  let tree

  context("when naem is 'Jest'", () => {
    const component = renderer.create(
      <App name='Jest' />
    )

    it("should display 'Hello Jest'", () => {
      tree = component.toJSON()
      expect(tree).toMatchSnapshot()
    })
  })
})
$ yarn test

 PASS  __tests__/components/App.spec.js
  <App />
    when naem is 'Jest'
      ✓ should display 'Hello Jest' (4ms)
    when naem is 'React'
      ✓ should display 'Hello Jest' (1ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   2 passed, 2 total
Time:        1.164s
Ran all test suites.

contextが使えるようになりましたー

Happy Hacking٩( ‘ω’ )و

Rails5でActiveSupport::PerThreadRegistryがdeprecatedになったよヘ(^o^)ノ

ちょっと今更ですが、Rails5でActiveSupport::PerThreadRegistryがdeprecatedになった。

ActiveSupport::PerThreadRegistryを使ったほうがイイ理由は遠い昔に書いたブログを参照してね。 murajun1978.hatenadiary.com

ActiveSupport::PerThreadRegistryにも書いてある、、

NOTE: This approach has been deprecated for end-user code in favor of thread_mattr_accessor and friends. Please use that approach instead.

thread_mattr_accessor を使えと

# ActiveSupport::PerThreadRegistry
class RuntimeRegistry
  extend ActiveSupport::PerThreadRegistry

  attr_accessor :api_runtime
end

# thread_mattr_accessor
class RuntimeRegistry
  thread_mattr_accessor :api_runtime
end

シンプルでいい感じヽ(´▽`)/

こういうのは都度対応しておかないと、バージョンアップの時にツラくなるのでサッと修正した方がいいね。

Happy Hacking٩( ‘ω’ )و

フロント用にサクッと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٩( ‘ω’ )و

n でNode.jsのバージョンを管理する ヘ(^o^)ノ

github.com

Installation

$ git clone git@github.com:tj/n.git
$ cd n && make install

Usage

Installed versions

$ n

Install latest version

$ n latest

Install/Activating versions

$ n 6.3.0

Available list

$ n ls

Remove version

$ n rm 6.3.0

io.js

$ n io [command]

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