Skip to content

Instantly share code, notes, and snippets.

View r7kamura's full-sized avatar

Ryo Nakamura r7kamura

View GitHub Profile
$ gem i json_world
Fetching: json_world-0.2.2.gem (100%)
Successfully installed json_world-0.2.2
1 gem installed
$ pry -r json_world
[1] pry(main)> class A
[1] pry(main)* include JsonWorld::DSL
[1] pry(main)* property(:x, type: Array, items: { type: String })
[1] pry(main)* end
=> [#<JsonWorld::PropertyDefinition:0x007f9fffa9bb08
var _ = require('lodash');
var Rx = require('rx');
(function () {
/**
* @param {HTMLElement} element
* @return {Rx.Observable}
*/
function createDeactivate$(element) {
return Rx.Observable.fromEvent(element, 'blur');
@r7kamura
r7kamura / NotImplementedError.md
Last active December 10, 2015 03:28
NotImplementedError

NotImpementedError

抽象クラスで、具象クラスに提供して欲しいメソッドを記述するときに使えそう。 単なるraiseでRuntimeErrorを発生させるよりは、意図の分かりやすさとStandardErrorに含まれない点で良い。

class AbstractCollector
  def collect
    raise NotImpementedError, "Implement #{self.class}#collect"
  end
end
@r7kamura
r7kamura / Forwardable.md
Last active December 10, 2015 03:28
about Forwardable module of Ruby

Forwardable

メソッドの委譲を実現する。 例えば内部的に配列を持ちながらCollectionを表現するクラスを作る場合、eachを配列に委譲すると便利。

require "forwardable"
class Collection
  extend Forwardable
  include Enumerable
@r7kamura
r7kamura / method-proxy.md
Last active December 10, 2015 03:28
Proxy all methods by BasicObject and method_missing

Proxy all methods

全てのメソッド呼出に対して何らかの処理を行うようなオブジェクトを生成したいとき、Rubyだと直接そういうオブジェクトを生成するようなクラスは用意されていないが、BasicObjectとmethod_missingを利用すれば簡単に作成できる。例えば、渡したloggerの全ての出力にタグを付けて欲しい場合にこの方法で解決しようとすると、こういう感じになる(この問題に対してのGoodな解決方法では無いです)。

class TaggingProxy < BasicObject
  def initialize(target)
    @target = target
  end

 def method_missing(name, message, *args, &amp;block)

Virtual Function on C++

C++における仮想関数について。C++のポリモーフィズムにおいて、仮想関数は重要な機能の1つ。

仮想関数

通常、子クラスは親クラスの提供する汎用的な機能を拡張していく形で構成する。 このとき、親クラスのメンバ関数を再定義することができる。 このような関数を仮想関数と呼ぶ。 仮想関数は、基本クラスで再定義可能であるということを明示する必要がある。

オーバーライド

@r7kamura
r7kamura / exhibit-pattern.md
Last active December 10, 2015 09:18
Exhibit Pattern in MVC

Exhibit Pattern in MVC

Rails等のMVC構造の中でExhibit Patternを用いる場合の一例。

Why

Exhibit Patternを何故用いるのか。

  1. 問題: MVCの中でも特にViewは煩雑になりがち
  2. 原因: Viewの中に複数の責任が同居しているからである
  3. 方針: ある側面でViewを捉え、特定の責任を別の層に切り分けるべきである

Fat Model

MVCにおけるModel肥大化への対策について

  • moduleへの分割
  • class への分割

moduleへの分割

ビジネスロジックをある単位で分割してmoduleに定義し、modelでincludeする

  • インターフェースは変更されない
require "mac-event-monitor"
monitor = Mac::EventMonitor::Monitor.new
monitor.add_listener(:key_down) do |event|
system("afplay #{ENV['HOME']}/bin/sounds/#{event.keycode % 14 + 1}.wav &")
end
monitor.run
@r7kamura
r7kamura / be_json_spec.rb
Created April 25, 2013 15:20
be_json_spec.rb
it "returns an array of resources" do
get "https://api.github.com/resource"
response.body.should be_json([
{
"url" => /^https:/,
"id" => /^\d+$/,
"description" => /gist/,
"public" => true,
"user" => Hash,
"files" => Hash,