2014년 4월 11일 금요일

[rails] as_json vs to_json

to_json => Returns a JSON string representing the model. Some configuration is available throughoptions.

모델을 표현하는 json string을 반환!

as_json => Returns a hash representing the model. Some configuration can be passed throughoptions.

model을 표현하는 hash를 반환!

2014년 2월 26일 수요일

[CSS] select box css style

custom select box를 구현
구현된 내용 : http://easytwitter.co.kr

CSS

.content-main{
  #sort-section{
    margin-right:20px;
    margin: 13px 0 0 200px;
    div.selectOptions {
      position:absolute;
      top:28px;
      left:0;
      width:198px;
      border:1px solid #ccc;
      border-bottom-right-radius:5px;
      border-bottom-left-radius:5px;
      overflow:hidden;
      background:#f6f6f6;
      padding-top:2px;
      display:none;
      z-index:9999;
    }
    span.selectOption {
      display:block;
      width:80%;
      line-height:20px;
      padding:5px 10%;
    }
    span.selectOption:hover {
      color:#f6f6f6;
      background:#4096ee;
    }
  }
  .selectBox{
    position:relative;
    display:inline-block;
    cursor:default;//마우스 오버될 때 커서 모양을 지정
    text-align:left;
    line-height:30px;
    clear:both;//float을 제거
    color:#888;
  }
  .selected{
    width:167px;
    text-indent:20px;
    border:1px solid #ccc;
    border-right:none;
    border-top-left-radius:5px;
    border-bottom-left-radius:5px;
    background:#f6f6f6;
    overflow:hidden;
  }
  span.selectArrow{
    width:30px;
    border:1px solid #60abf8;
    border-top-left-radius:5px;
    border-bottom-left-radius:5px;
    text-align:center;
    font-size:20px;
    //사용자는 어떤 content도 선택할 수 없다. 
    -webkit-user-select:none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -o-user-select: none;
    user-select: none;
    background:#60abf8;
  }
  span.selectArrow,span.selected {
    position:relative;
    float:left;
    height:30px;
    z-index:1;
    color:#333;
  }
}

JQUERY

(enableSelectBoxes = ->
      $("div.selectBox").each ->
        $(this).children("span.selected").html $(this).children("div.selectOptions").children("span.selectOption:first").html()
        $(this).attr "value", $(this).children("div.selectOptions").children("span.selectOption:first").attr("value")
        $(this).children("span.selected,span.selectArrow").click ->
          if $(this).parent().children("div.selectOptions").css("display") is "none"
            $(this).parent().children("div.selectOptions").css "display", "block"
          else
            $(this).parent().children("div.selectOptions").css "display", "none"
          return
        $(this).find("span.selectOption").click ->
          $(this).parent().css "display", "none"
          $(this).closest("div.selectBox").attr "value", $(this).attr("value")
          $(this).parent().siblings("span.selected").html $(this).html()
          $(".content-main .content-header .header-inner").removeAttr("style")
          return
        return
      return
    )() 

2014년 1월 7일 화요일

[javascript] curry

안녕하세요 belhyun입니다.
curry 메소드는 함수와 인자를 결합해 새로운 함수를 만듭니다.

  var combine = { 
    'curry': function(fn){
      var args = nativeSlice.call(arguments, 1); 
      return function(){
        return fn.apply(this, args.concat(nativeSlice.call(arguments)));
      };  
    }   
  }; 

다음의 사용예를 들어보겠습니다.

combine.curry(function(){},[1,2])([3,4]);

위의 코드는 curry를 사용한 것인데 최종적으로 function(){}에 파라미터로 [1,2,3,4]가 전달됩니다. 즉 전달된 함수에 인자를 결합해 새로운 함수를 만들어 냅니다.
코드를 보게되면 nativeSlice는 Array.prototype.slice입니다. 전달된 [1,2]를 slice 하게 되면 [1,2]가 args에 할당됩니다. 그리고 클로져 함수에서는 [3,4]를 arguments로 받아 slice 후, args와 concat합니다. 즉 [1,2,3,4]가 function(){}에 전달됩니다. 즉 전달된 파라미터 함수에 인자를 결합하여 새로운 함수를 반환되게 합니다.

감사합니다.

2014년 1월 3일 금요일

[ROR] class << self

안녕하세요 belhyun입니다. ruby는 metaclass라고 하는 문법을 가지고 있습니다. 이에 대해 알아보도록 하겠습니다. 먼저 코드를 보도록 하겠습니다.
class Belhyun
  class << self
    def belhyun2
     p 'belhyun2'
    end
  end
end

Belhyun.belhyun2

위 결과 값은 'belhyun2'입니다.
class << self는 Belhyun에 대한 싱글턴 객체를 열게(open up) 됩니다. 그리고 위 구문은 이 싱글턴 객체에 메소드를 재정의하게 됩니다. 즉 Belhyun에 static 메소드를 정의한 것과 같은 효과를 내게 됩니다. 주로 사용되는 곳도 static 메소드를 정의할 때 사용됩니다.

[ROR] yield self

안녕하세요 belhyun입니다.
ROR에서 module이나 class 내부에서 yield self를 사용할 수 있습니다.
yield self의 의미는 호출된 block을 호출하고 그 파라미터로 self를 던진다는 의미입니다. 다음의 예를 통해 알아보도록 하겠습니다.
class Pokemon
  def initialize(move)
    @move = move
  end
 
  def battle
    yield self
  end
 
  def use_move
    puts "used #{@move}!"
  end
end
 
mewtwo = Pokemon.new "Psychic"
 
mewtwo.battle do |m2|
  m2.use_move
end
 
# => used Psychic!
 
arceus = Pokemon.new "Judgement"
 
arceus.battle do |arc|
  arc.use_move
end

위 클래스를 보면 battle 메소드에서 yield self가 사용되고 있음을 확인할 수 있습니다.
먼저 Pokemon의 인스턴스인 mewtwo의 메소드인 battle에 block을 전달합니다. 이 블락은 yield self를 만나 실행되게 됩니다. 단 이 block에 전달되는 파라미터는 self입니다. 그렇기 때문에 m2에 self가 바인딩됩니다. 이어서 self의 use_move가 호출되는데 이 메소드에서는 인스턴스 변수인 @move에 접근합니다. 그렇기 때문에 결과적으로 used Psychic!이 호출됩니다. 아래의 코드도 같은 의미로 해석할 수 있습니다.

감사합니다.

2014년 1월 1일 수요일

[OAUTH] oauth_nonce, signature

안녕하세요 belhyun입니다.
twitter api를 사용하는 도중 모르는 용어가 더럿 있어 정리해 봅니다.

oauth_nonce

정의

oauth_nonce 파라미터는 각각의 유일한 요청마다 앱이 생성시켜야 하는 토큰입니다. 트위터는 이 값을 요청이 여러번 되었는지 판단하게 됩니다. base64로 인코딩된 32바이트의 랜덤 데이터로 생성됩니다.

생성방법

1. 32 바이트의 랜덤 문자열을 생성합니다. 이 때, "!" "#" "$"등은 제거합니다. 예를들어 aAbAaB..의 형태로 생성합니다.
2. 문자열을 utf8로 인코딩합니다.
3. base64로 인코딩합니다.

signature

정의

oauth_signature 파라미터는 동작되고 있는 다른 모든 리퀘스트 파라미터와 signing 알고리즘을 통한 2개의 secret 값에 의해 생성되어지는 값입니다. 이 값의 목적은 요청중에 요청이 변조되지 않고, 어플리케이션에서 요청하는 것을 확인하고 어플리케이션이 사용자의 계정과 상호작용하는 인증을 가지고 있음을 확인하기 위해서입니다. 

생성방법

https://dev.twitter.com/docs/auth/creating-signature 에 tutorial로 기술되어 있습니다.

감사합니다.

2013년 12월 30일 월요일

[ROR] virtual attributes

안녕하세요 belhyun입니다.
rails에서는 model에서 virtual attributes를 사용할 수 있습니다.
예를 들어, model field의 이름이 name이라고 해보겠습니다.
만약 name에 @을 붙인 name을 attribute를 요청하고 싶을 때 virtual attributes를 사용하게 됩니다.

먼저 @을 붙인 이름을 twitter_name으로 정의하고 해당 이름에 대한 gettter/setter를 정의합니다.

attr_accessor: twitter_name

그런 후, get 메소드에서 해당하는 형태로 정의합니다.

def twitter_name
  "@{name}"
end

위와 같이 지정한 후 만약 name 필드가 User Model에 정의되었다면 User.twitter_name을 호출하게 되면 @을 붙인 문자열이 반환됩니다. 이러한 virtual attributes를 사용하여 좀 더 확장성 있는 표현을 할 수 있게 됩니다.

감사합니다.