gist

2012年10月14日日曜日

Mac OS X Mountain Lion (10.8.2) に Rails 3.2.8 をインストールする

約100日ぶりの更新です。
RailsとiOS/Androidアプリとクラウド3点セットのお仕事が増えてきましたので、少しNode.jsから離れて、更新を続けようと思います。

Moutain LionにRailsをインストールしたときの作業のログです。
Rubyのバージョン管理ツールにrbenvを使用しています。

事前準備

  • AppStoreでXcode 4.5.1 をインストールしておく
  • Xcode 4.5.1の設定からCommand Line Tools をインストールしておく

Homebrewをインストールする

rbenvをインストールする

.bash_profileを編集して以下の一行を追加します。

$ vim ~/.bash_profile

再読込を忘れずに

ruby-buildをインストール

rbenv install -l でインストール可能なバージョンのリストが表示されればOKです。

Rubyをインストールする

使用しているrubyのバージョンが1.9.3-p194でパスが変更されていればOK。

Railsをインストールする

Railsアプリを作成する

ブラウザから http://localhost:3000/ にアクセスして以下の画面が表示されたRailsのインストールは完了です。

2012年7月2日月曜日

CoffeeScriptで学ぶ Underscore.js 15(Chain編)

CoffeeScriptで学ぶUnderscore.js(Chain編)。今回で15回目、ようやく最終回です。


chain

_.chain(object)

chainは、underscoreのメソッドを次々と連結して実行できる便利なメソッドです。

_ = require 'underscore'

users = [
 {name : 'curly', age : 25}, 
 {name : 'moe', age : 21}, 
 {name : 'larry', age : 23}
]

youngest = 
 _.chain(users)
 .sortBy (user)->
  user.age
 .map (user)->
  user.name + ' is ' + user.age
 .first()
 .value()

console.log youngest
実行結果
$ coffee chain.coffee 
moe is 21

_.chain(users)でchainに配列を与えています。次にsortByでage順に並べます。次のmapで「◯◯ is 年齢」の出力を作成します。firstで最初の行を取得し、最後にvalueで値にしています。

Underscore.jsでは、

_.map [1,2,3], (n)->
 n * 2

は、以下のようにも記述できます。

_([1,2,3]).map (n)->
 n * 2

ですので、上記のchainの部分は以下のように分解できます。

sorted = _(users).sortBy (user)->
 user.age
mapped = _(sorted).map (user)->
 user.name + ' is ' + user.age
first = _(mapped).first()
value = _(first).value()

value

_(obj).value()

valueは、objを展開します。chainの最後に負荷することで値として展開できます。

_ = require 'underscore'

console.log _([3,2,6]).value()
実行結果
$ coffee value.coffee 
[ 3, 2, 6 ]

Underscore.jsは、JavaScriptを強力にサポートするパッケージです。是非とも使いこなしてみましょう。


関連ページ

2012年6月30日土曜日

CoffeeScriptで学ぶ Underscore.js 14(Template編)

CoffeeScriptで学ぶ、Underscore.js。このエントリーで14回目です。今回はTemplate編。Underscore.jsが最も普及したのも、このtemplateがあったからのように思えます。templateは、公式サイトでも気合の入った説明がされています。


template

_.template(templateString,[data],[settings])

templateは、JavaScriptテンプレートをコンパイルし、レンダリングします。JSONデータソースからHTMLの一部をレンダリングするのに使われています。Template関数では、変数を出力する場合は、<%= ... %>を使います。JavaScriptのコードを実行するには、<% ... %>を使います。HTMLエスケープしたい場合、<%- ... %>を使います。

_ = require 'underscore'

template = _.template "hello <%= name %>"
console.log template {name: 'miku'}

list = '''
<% _.each(people, function(name) { %>
<li><%= name %></li>
<% }); %> 
'''
template = _.template list, {people:['MIKU', 'RIN', 'LEN']}
console.log template

template = _.template '<b><%- value %></b>'
console.log template {value: '<script>'}
実行結果
$ coffee template.coffee 
hello miku

  • MIKU
  • RIN
  • LEN
  • &lt;script&gt;

    templateSettings関数を使うと、テンプレートを書き換えることができます。テンプレートとしてメジャーなMustache.jsスタイルのテンプレートにするには以下のように指定します。

    _ = require 'underscore'
    
    _.templateSettings =
      interpolate : /\{\{(.+?)\}\}/g
    
    template = _.template "Hello {{ name }}!"
    console.log template {name : "Mustache"}
    
    実行結果
    $ coffee templateSettings.coffee 
    Hello Mustache!
    

    関連ページ

    2012年6月27日水曜日

    CoffeeScriptで学ぶ Underscore.js 13(Utility編)

    いよいよUtility編。大詰めです。


    noConflict

    _.noConflict

    noConflictは、変数である「_」(アンダースコア)を別の変数に置き換えることができます。Underscoreのオブジェクトを返します。

    _ = require 'underscore'
    
    underscore = _.noConflict()
    
    _ = 10
    
    console.log _
    console.log underscore
    
    実行結果
    $ coffee noConflict.coffee 
    10
    { [Function]
      _: [Circular],
      VERSION: '1.3.3',
      forEach: [Function],
      each: [Function],
      collect: [Function],
      map: [Function],
    ...
    

    identity

    _.identity(value)

    identityは、valueを与えたとき、返り値としてそのままvalueを返します。underscoreの初期のイテレータに利用されているそうな。

    _ = require 'underscore'
    
    moe = {name:'moe'}
    
    console.log moe is _.identity moe
    
    実行結果
    $ coffee identity.coffee 
    true
    

    times

    _.times(n, iterator)

    timesは、iteratorをn回実行します。

    _ = require 'underscore'
    
    _.times 10, ()->
     console.log 'hello'
    
    実行結果
    $ coffee times.coffee 
    hello
    hello
    hello
    hello
    hello
    hello
    hello
    hello
    hello
    hello
    

    mixin

    _.mixin(object)

    mixinは、Underscoreにカスタマイズした関数を追加することができます。{関数名:関数} というオブジェクトを追加することで、Underscoreのオブジェクトとして定義できます。

    _ = require 'underscore'
    
    _.mixin {
     capitalize:(string)->
      string.charAt(0).toUpperCase() + string.substring(1).toLowerCase()
    }
    
    console.log _.capitalize "underscore"
    
    実行結果
    $ coffee mixin.coffee 
    Underscore
    

    uniqueId

    _.uniqueId([prefix])

    uniqueIdは、グローバル域で一意なIDを生成します。引数にプレフィックスを与えることができます。

    _ = require 'underscore'
    
    console.log _.uniqueId()
    console.log _.uniqueId()
    console.log _.uniqueId()
    console.log _.uniqueId()
    console.log _.uniqueId('CB')
    
    実行結果
    $ coffee uniqueId.coffee 
    0
    1
    2
    3
    CODE4
    

    escape

    _.escape(string)

    escapeは、HTMLなどの&, <, >, &quat;, ', / をエスケープ処理して返します。

    _ = require 'underscore'
    
    console.log _.escape '&,<,>,&quat;,\',/'
    
    実行結果
    $ coffee escape.coffee 
    &amp;,&lt;,&gt;,&quot;,&#x27;,&#x2F;
    

    result

    _.result(object, property)

    resultは、指定したobjectのプロパティを返します。プロパティが値の場合はそのまま値が、関数の場合、その関数を実行します。

    _ = require 'underscore'
    
    hoge = 
     foo: 'hello'
     bar: ()->
      'good morning'
    
    console.log _.result hoge, 'foo'
    console.log _.result hoge, 'bar'
    
    実行結果
    $ coffee result.coffee 
    hello
    good morning
    

    関連ページ

    2012年6月25日月曜日

    CoffeeScriptで学ぶ Underscore.js 12(Object編)

    12回目。Object編。今回はis判定です。16種類の判定があります。


    isEqual

    _.isEqual(object, other)

    isEqualは、2つのオブジェクトの最下層まで等しい場合trueを返します。

    _ = require 'underscore'
    
    a = {name:'Taro', luckyNumbers:[12,67,42]}
    b = {name:'Taro', luckyNumbers:[12,67,42]}
    
    console.log a is b
    console.log _.isEqual a,b
    
    実行結果
    $ coffee isEqual.coffee 
    false
    true
    

    isEmpty

    _.isEmpty(object)

    isEmptyは、objectが空の場合にtrueを返します。

    _ = require 'underscore'
    
    a = {}
    b = {a}
    
    console.log _.isEmpty a
    console.log _.isEmpty b
    
    実行結果
    $ coffee isEmpty.coffee 
    true
    false
    

    isElement

    _.isElement(object)

    isElementは、オブジェクトがDOM要素である場合にtrueを返します。

    alert _.isElement(jQuery('body')[0]);
    
    実行結果
    true
    

    ブラウザでjQueryを読み込んで、実行します。


    isArray

    _.isArray(object)

    isArrayは、objectが配列のときtrueを返します。

    _ = require 'underscore'
    
    list = [1,2,3,4,5]
    obj = {list}
    
    console.log _.isArray list
    console.log _.isArray obj
    
    実行結果
    $ coffee isArray.coffee 
    true
    false
    

    isObject

    _.isObject(value)

    isObjectは、objectがオブジェクトの場合、trueを返します。

    _ = require 'underscore'
    
    list = [1,2,3,4,5]
    obj = {list}
    
    console.log _.isObject list
    console.log _.isObject obj
    console.log _.isObject 100
    
    実行結果
    $ coffee isObject.coffee 
    true
    true
    false
    

    配列もtrueです。


    isArguments

    _.isArguments(object)

    isArgumentsは、objectが引数の場合、trueを返します。

    _ = require 'underscore'
    
    func = ()->
     _.isArguments arguments
    
    console.log func(1,2,3)
    
    console.log _.isArguments([1,2,3])
    
    実行結果
    $ coffee isArguments.coffee 
    true
    false
    

    isFunction

    _.isFunction(object)

    isFunctionは、objectが関数の場合trueを返します。

    _ = require 'underscore'
    
    console.log _.isFunction _.isFunction
    console.log _.isFunction 123
    
    実行結果
    $ coffee isFunction.coffee 
    true
    false
    

    isString

    _.isString(object)

    isStringは、objectが文字列の場合、trueを返します。

    _ = require 'underscore'
    
    console.log _.isString 'AKB'
    console.log _.isString 123
    
    実行結果
    $ coffee isString.coffee 
    true
    false
    

    isNumber

    _.isNumber(object)

    isNumberは、objectが数値の場合、trueを返します。

    _ = require 'underscore'
    
    console.log _.isNumber 'AKB'
    console.log _.isNumber 123
    
    実行結果
    $ coffee isNumber.coffee 
    false
    true
    

    isFinite

    _.isFinite

    isFiniteは、objectが有限の数値の場合trueを返します。

    _ = require 'underscore'
    
    console.log _.isFinite -Infinity
    console.log _.isFinite 123
    
    実行結果
    $ coffee isFinite.coffee 
    false
    true
    

    isBoolean

    _.isBoolean(object)

    isBooleanは、objectがtrueかfalseの場合にtrueを返します。

    _ = require 'underscore'
    
    console.log _.isBoolean null
    console.log _.isBoolean true
    console.log _.isBoolean false
    
    実行結果
    $ coffee isBoolean.coffee 
    false
    true
    true
    

    falseはBoolean型なのでtrueを返します。


    isDate

    _.isDate(object)

    isDateは、objectがDate型のときtrueを返します。

    _ = require 'underscore'
    
    console.log _.isDate new Date()
    
    実行結果
    $ coffee isDate.coffee 
    true
    

    isRegExp

    _.isRegExp(object)

    isRegExpは、objectが正規表現となっている場合trueを返します。

    _ = require 'underscore'
    
    console.log _.isRegExp /abc/
    
    実行結果
    $ coffee isRegExp.coffee 
    true
    

    isNaN

    _.isNaN(object)

    isNaNは、objectがNaN型の場合、trueを返します。undefinedの場合、ネイティブのisNaN ではtrueを返しますが、_.isNaNではfalseを返します。

    _ = require 'underscore'
    
    console.log _.isNaN NaN
    console.log _.isNaN undefined
    console.log isNaN undefined
    
    実行結果
    $ coffee isNaN.coffee 
    true
    false
    true
    

    isNull

    _.isNull(object)

    isNullは、objectがnullの場合、trueを返します。

    _ = require 'underscore'
    
    console.log _.isNull null
    console.log _.isNull undefined
    
    
    実行結果
    $ coffee isNull.coffee 
    true
    false
    

    isUndefined

    _.isUndefined(object)

    isUndefinedは、objectがundefinedの場合、trueを返します。

    _ = require 'underscore'
    
    console.log _.isUndefined null
    console.log _.isUndefined undefined
    
    実行結果
    $ coffee isUndefined.coffee 
    false
    true
    

    関連ページ

    2012年6月19日火曜日

    CoffeeScriptで学ぶ Underscore.js 11(Object編)

    第11回。Object編に入りました。


    keys

    _.keys(object)

    keysは、オブジェクト内のすべてのキーを配列にして返します。

    _ = require 'underscore'
    
    console.log _.keys {
     hoge: 'hoge'
     seven: 7
     bool: true
    }
    
    実行結果
    $ coffee keys.coffee 
    [ 'hoge', 'seven', 'bool' ]
    

    values

    _.values(object)

    valuesは、オブジェクト内のすべての値を配列にして返します。

    _ = require 'underscore'
    
    console.log _.values {
     hoge: 'hoge'
     seven: 7
     bool: true
    }
    
    実行結果
    $ coffee values.coffee 
    [ 'hoge', 7, true ]
    

    functions

    _.functions(object)

    functionsは、object内に存在するすべての関数をソートして配列を返します。

    _ = require 'underscore'
    
    console.log _.functions _
    
    実行結果
    $ coffee functions.coffee 
    [ '_',
      'after',
      'all',
      'any',
      'bind',
      'bindAll',
      'chain',
      'clone',
      'collect',
      'compact',
      'compose',
      ...
    

    extend

    _.extend(destination, *sources)

    extendは、sourcesに指定したオブジェクト内のすべてのプロパティをdestinationに統合します。destinationで既に指定済みのプロパティがあった場合、sourcesのプロパティで上書きされます。

    _ = require 'underscore'
    
    extended = _.extend {
     hoge: 'extend hoge'
     hello: (name)->
      'Hello, ' + name
    }, {
     hoge: 'hoge'
     bool: false
     seven: 7
     hello: ()->
      'Hello'
    }, {
     bool: true
    }
    
    
    console.log 'hoge=' + extended.hoge
    console.log 'seven=' + extended.seven
    console.log 'bool=' + extended.bool
    console.log 'hello=' + extended.hello('Moe!')
    
    実行結果
    $ coffee extend.coffee 
    hoge=hoge
    seven=7
    bool=true
    hello=Hello
    

    pick

    _.pick(object, *keys)

    pickは、オブジェクトの中のうち、キーを指定するとプロパティをコピーしてオブジェクトを返します。

    _ = require 'underscore'
    
    pickked = _.pick {
     'name':'山田 太郎'
     'yomi':'やまだ たろう'
     'email':'taro@yamada.me'
    }, 'name', 'email'
    
    console.log pickked
    
    実行結果
    $ coffee pick.coffee 
    { name: '山田 太郎', email: 'taro@yamada.me' }
    

    defaults

    _.defaults object, *defualts

    defaultsは、オブジェクトのデフォルト値を決める時に使います。

    _ = require 'underscore'
    
    defaults = {
     'hp':20
     'mp':5
     'items':['やくそう']
     'weapons':['こんぼう']
    }
    
    hero = _.defaults {'hp':100,'weapons':['銅の剣']}, defaults
    
    console.log hero
    
    実行結果
    $ coffee defaults.coffee 
    { hp: 100, weapons: [ '銅の剣' ], mp: 5, items: [ 'やくそう' ] }
    

    clone

    _.clone(object)

    cloneは、オブジェクトのシャドウコピーを作成して返します。ネストされたオブジェクトや配列は、参照がコピーされ複製はされません。

    _ = require 'underscore'
    
    hero = {'name':'moe', 'items':[{'name':'銅の剣', 'count':5}]}
    clonedHero = _.clone hero
    
    console.log clonedHero
    
    # クローンのネストされたオブジェクトを変更すると、、、
    clonedHero.items[0].name = 'こんぼう' 
    
    console.log hero
    
    実行結果
    $ coffee clone.coffee 
    { name: 'moe', items: [ { name: '銅の剣', count: 5 } ] }
    { name: 'moe', items: [ { name: 'こんぼう', count: 5 } ] }
    

    tap

    _.tap(object, interceptor)

    tapは、オブジェクトに対して割り込み処理を実行します。このメソッドは、chainメソッドの中ですぐに結果を処理する場合に利用されるのを目的としています。

    _ = require 'underscore'
    
    results = _.chain [1,2,3,100]
    .filter (num)->
     (num % 2) is 0
    .tap(console.log)
    .map (num)->
     num * num
    .value()
    
    console.log results
    
    実行結果
    $ coffee tap.coffee 
    [ 2, 100 ]
    [ 4, 10000 ]
    

    関連ページ

    2012年6月18日月曜日

    CoffeeScriptで学ぶ Underscore.js 10(Function編)

    Underscore.js、10回目。Function編です。


    throttle

    _.throttle(function, wait)

    throttleは、waitで指定したミリ秒に1回だけfunctionを実行します。

    _ = require 'underscore'
    
    hello = ()->
     console.log 'Hello!'
    
    throttled = _.throttle hello, 1000
    
    for x in [1..100000]
     do ()->
      throttled()
    
    
    実行結果
    $ coffee throttle.coffee 
    Hello!
    Hello!
    

    Hello!が1秒ごとに表示されます。


    debounce

    _.debounce(function, wait, [immediate])

    debounceは、waitで指定したミリ秒が経過するまでfunctionを繰り返し呼ばれないようにします。

    _ = require 'underscore'
    
    hello = ()->
     console.log 'Hello!'
    
    lazyFunc = _.debounce hello, 1000
    
    lazyFunc()
    
    
    実行結果
    $ coffee debounce.coffee 
    Hello!
    

    once

    _.once(function)

    onceは、関数を1回しか呼ばれないようにすることができます。

    _ = require 'underscore'
    
    createApplication = ()->
     console.log 'Initialize!'
    
    initialize = _.once createApplication
    
    initialize()
    initialize()
    
    実行結果
    $ coffee once.coffee 
    Initialize!
    

    after

    _.after(count, function)

    afterは、countで指定された回数だけfunctionが呼ばれると初めて実行されます。

    _ = require 'underscore'
    
    hello = ()->
     console.log 'Hello!'
    
    after = _.after(5, hello);
    
    after()
    after()
    after()
    after()
    after()
    
    
    実行結果
    $ coffee after.coffee 
    Hello!
    

    wrap

    _.wrap(function, wrapper)

    wrapは、functionで指定した関数をwrapperの中で使うことができます。

    _ = require 'underscore'
    
    hello = (name)->
     'Hello, ' + name
    
    wrapped = _.wrap hello, (func)->
     "before: " + func('World') + " : after"
    
    console.log wrapped()
    実行結果
    $ coffee wrap.coffee 
    before: Hello, World : after
    

    compose

    _.compose(*functions)

    composeは、複数の関数を与えると合成関数として返します。f(), g(), h()を合成すると、f(g(h())) を返します。

    _ = require 'underscore'
    
    hello = (name)->
     'Are you ' + name
    
    question = (statement)->
     statement + '?'
    
    who = _.compose hello, question
    
    
    console.log who('moe')
    
    実行結果
    $ coffee compose.coffee 
    Are you moe?
    

    関連ページ