如何在Ruby中干掉两个函数?

时间:2014-07-02 18:07:50

标签: ruby ruby-on-rails-3

通过将两个函数共享的三行移动到另一个函数,有没有办法干掉这两个Ruby函数?

def format_currency(number)
  number_to_currency(number, 
    :unit       => current_user.currency_unit, 
    :delimiter  => current_user.currency_delimiter, 
    :separator  => current_user.currency_separator, 
    :format     => current_user.currency_format
  )
end

def format_currency_for_pdf(number, invoice)    
  number_to_currency(number / invoice.exchange_rate, 
    :unit       => CURRENCIES[invoice.currency]
    :delimiter  => current_user.currency_delimiter, 
    :separator  => current_user.currency_separator, 
    :format     => current_user.currency_format
  )
end

感谢您的帮助?

2 个答案:

答案 0 :(得分:2)

def format_currency(number)
  number_to_currency(number, 
    currency_hash(current_user.currency_unit) 
  )
end

def format_currency_for_pdf(number, invoice)    
  number_to_currency(number / invoice.exchange_rate, 
    currency_hash(CURRENCIES[invoice.currency])
  )
end

def currency_hash(unit)
  {
    :unit       => unit,
    :delimiter  => current_user.currency_delimiter, 
    :separator  => current_user.currency_separator, 
    :format     => current_user.currency_format
  }
end

答案 1 :(得分:2)

正如芋头所说,它将是:

def format_currency(number)
  number_to_currency(number,
    currency_hash(current_user.currency_unit)
  )
end

def format_currency_for_pdf(number, invoice)
  number_to_currency(number / invoice.exchange_rate,
    currency_hash(CURRENCIES[invoice.currency])
  )
end

def currency_hash unit
  {
    :unit       => unit,
    :delimiter  => current_user.currency_delimiter,
    :separator  => current_user.currency_separator,
    :format     => current_user.currency_format
  }
end