12

次のようなコードがあります。

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

しかし、これは機能しません。モデルで がすでに定義されている場合、 Railspriceは「スタック レベルが深すぎます」と報告します。def pricedef amountnumber_to_currency

4

6 に答える 6

41

アプリケーション全体のデフォルトを変更したい場合は、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

単位以外はすべてオプションであり、デフォルトに戻りますが、変更できる値がわかるように入れました。£ の代わりに £ 記号を使用することもできます。

于 2010-12-14T03:01:10.893 に答える
2

これがこの問題への私のアプローチでした..

# /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

次に、ビューをすべて更新するには、アプリ ヘルパーの 1 つにモジュールを含めます

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

これで、数値から通貨へのヘルパーを使用するすべての場所で、ポンド記号でフォーマットされますが、元の Rails メソッドのすべての柔軟性も備えているため、以前と同じようにオプションを渡すことができます..

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

ドル記号に戻します。

于 2009-11-03T11:17:31.217 に答える
1

繰り返しを単純化するために別のヘルパーメソッドquid(price)を作成することに関する他の答えは、おそらく最良のアプローチです。ただし、モデル内のビューヘルパーに本当にアクセスしたい場合は、次のようにすることができます。

# /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
于 2009-09-09T15:27:49.963 に答える
1

Rails 3以降

ラリーKが説明しているように、この編集で:

def quid(price)
   number_to_currency(price, :unit => "&pound;")
 end
于 2011-02-09T17:12:40.233 に答える