문제

나는 다음과 유사한 코드를 가지고 있습니다.

number_to_currency(line_item.price, :unit => "£")

다양한 모델에서 내 견해를 쓰러 뜨립니다. 내 응용 프로그램은 GBP (£)에서만 처리되므로 각 모델로 이동하지 않아야합니다. line_item.price 문자열을 반환해야합니다 (예 :) number_to_currency(line_item.price, :unit => "£") 그리고 line_item.price 동일합니다. 나는 이것을하기 위해서야한다고 생각한다.

def price
 number_to_currency(self.price, :unit => "£")
end

그러나 이것은 작동하지 않습니다. 만약에 price 모델에 이미 정의 된 다음 Rails는 '스택 레벨이 너무 깊어'보고됩니다. def price 에게 def amount, 그런 다음 불평합니다 number_to_currency 정의되지 않았습니까?

도움이 되었습니까?

해결책

숫자 _to_currency는 뷰 도우미이므로 모델에서 사용할 수 없습니다.

Application_helper.rb에서 자신의 도우미를 정의하여 키 스트로크를 저장할 수 있습니다 (따라서 모든보기에서 사용할 수 있습니다). 예를 들어

def quid(price)
  number_to_currency(price, :unit => "£")
end

그런 다음보기에서 호출하십시오.

quid(line_item.price)

다른 팁

전체 응용 프로그램의 기본값을 변경하려면 Config/Locales/en.yml을 편집 할 수 있습니다.

내 것 같아요 :

# Sample localization file for English. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
"en":
  number:
    currency:
        format:
            format: "%u%n"
            unit: "£"
            # These three are to override number.format and are optional
            separator: "."
            delimiter: ","
            precision: 2

장치를 제외한 모든 것은 선택 사항이며 기본값으로 돌아갑니다. 그러나 어떤 값을 변경할 수 있는지 알 수 있습니다. £ 대신 £ 부호를 사용할 수도 있습니다.

그 이유 스택 레벨이 너무 깊습니다 오류는 당신이 말할 때입니다 self.price 에서 price 방법 정상 액세서 메소드를 재정의 했으므로 가격 방법에 대한 무한 재귀 호출을 생성하고 있습니다. 이를 피하려면 속성 해시를 사용하여 가격 필드의 값에 액세스해야합니다. eg와 같은 것 :

def price
 number_to_currency(attributes['price'], :unit => "£")
end

사실을 제외하고 number_to_currency Larry K가 설명하는 이유는 모델 코드에서 사용할 수 없습니다.

이 문제에 대한 나의 접근 방식은 다음과 같습니다 ..

# /RAILS_ROOT/lib/app_name/currency_helper.rb
module AppName
  module CurrencyHelper    

    include ActionView::Helpers::NumberHelper

    def number_to_currency_with_pound(amount, options = {})
      options.reverse_merge!({ :unit => '£' })
      number_to_currency_without_pound(amount, options)
    end

    alias_method_chain :number_to_currency, :pound

  end
end

당신의 모델에서 당신은 이것을 할 수 있습니다 (그리고 당신은 당신이 사용하지 않을 방법으로 모델을 오염시키지 않을 것입니다).

class Album < ActiveRecord::Base
  include AppName::CurrencyHelper

  def price
    currency_to_number(amount)
  end
end

그런 다음 모든 내용에 대한 의견이 업데이트 되려면 앱 도우미 중 하나의 모듈이 포함됩니다.

module ApplicationHelper
   # change default currency formatting to pounds..
   include AppName::CurrencyHelper
end

이제 숫자에 통화 헬퍼를 사용하는 곳마다 파운드 기호로 형식화되지만 원래 레일 방법의 모든 유연성이 있으므로 이전과 마찬가지로 옵션을 전달할 수 있습니다.

number_to_currency(amount, :unit => '$')

다시 달러 기호로 다시 변환합니다.

반복을 단순화하기 위해 다른 도우미 방법 quid (가격)를 만드는 것과 관련하여 다른 대답은 아마도 최선의 접근법 일 것입니다. 그러나 모델에서 도우미를 실제로 액세스하려면 다음과 같은 작업을 수행 할 수 있습니다.

# /RAILS_ROOT/lib/your_namespace/helper.rb
#
# Need to access helpers in the model?
# YourNamespace::Helper.instance.helper_method_name
module YourNamespace
  class Helper
    include Singleton
    include ActionView::Helpers
  end
end

그런 다음 모델 클래스 에서이 작업을 수행 할 수 있어야합니다.

def price
  helper = YourNamespace::Helper.instance
  helper.number_to_currency(read_attribute('price'), :unit => "£")
end

레일 3

Larry K가 설명하지만이 편집을 통해 다음과 같습니다.

def quid(price)
   number_to_currency(price, :unit => "&pound;")
 end
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top