DonutWorks / Ari

0 stars 0 forks source link

문자열(String)과 심볼(Symbol)을 구분해서 사용하기 #334

Open shaynekang opened 9 years ago

shaynekang commented 9 years ago

루비에는 심볼(Symbol)이라는 데이터형이 존재합니다.

쉽게 말해 C언어의 const string이라고 보시면 됩니다. ㅎㅎ 문자열 값을 수정하지 않고, 주로 비교하는 용도로 사용할 경우 심볼을 활용하는 것이 좋습니다. 가령

class NoticesController < ApplicationController
  def show
    @notice = Notice.find_by_id(params[:id]) or not_found
    current_user.read!(@notice)

    case @notice.notice_type
    when "external"
      redirect_to @notice.link
    when "survey"
      redirect_to notice_responses_path(@notice)
    when "to"
      redirect_to notice_to_responses_path(@notice)
    else

    end

    # plain -> notices/show
  end
end

의 코드는 다음과 같이 수정한다면 좋겠죠.

class NoticesController < ApplicationController
  def show
    @notice = Notice.find_by_id(params[:id]) or not_found
    current_user.read!(@notice)

    case @notice.notice_type
    when :external
      redirect_to @notice.link
    when :survey
      redirect_to notice_responses_path(@notice)
    when :to
      redirect_to notice_to_responses_path(@notice)
    else

    end

    # plain -> notices/show
  end
end

경우에 따라서는 모델의 DB컬럼 값이 문자열로 되어있어서 심볼을 반환하지 못하는 경우도 있습니다. 이런 경우는 모델에서 컬럼값의 reader를 재정의해주면 됩니다.

class Notice < ActiveRecord::Base
  def notice_type
    value = read_attribute(:notice_type)

    # value가 nil이면 아무것도 하지 않고 반환, nil이 아니면 value.to_sym 호출
    value.try(:to_sym)
  end
end
irb(main):132:0> Notice.new(notice_type: nil).notice_type
=> nil
irb(main):133:0> Notice.new(notice_type: :to).notice_type
=> :to

다른 코드도 살펴보고 비슷한 상황이 있다면 수정하면 좋겠습니다. ㅎㅎ