bsn
bsn

Reputation: 1054

ruby on rails: can't understand code

I'm newbie in ruby on rails, trying to rewrite rails project in PHP, can someone explain me please what next lines of code do?

  def payment_types_billing
    I18n.t("customer.payment_types_billing").inject({}){|memo,(k,v)|
      memo[k.to_s.to_i] = v; memo}.
        merge({
           PaymentType::ACCOUNTCREDIT => I18n.t("customer.payment_types_billing.#{PaymentType::ACCOUNTCREDIT}", 
           :amount => number_to_currency(get_account_credit))
        })
  end

I don't understand part after .inject, if someone can just explain that part in human language, I will be very thankful. :)

Upvotes: 0

Views: 73

Answers (1)

ConnorCMcKee
ConnorCMcKee

Reputation: 1645

These methods work in conjunction. By calling payment_types, the following will occur:

First it grabs a section of the localization yaml (likely in config/locales/en.yml). For more on internationalization/localization, see this!

I18n.t("customer.payment_types_billing")

Then it runs an inject block on the resulting enumerable (in this case a hash), with the intent of returning a newly-formed result (see about .inject here)

.inject({}){|memo,(k,v)| memo[k.to_s.to_i] = v; memo}

The result of this block appears to be a hash whose keys were the keys of the retrieved hash, converted to integers (without knowing the data being accessed, I can't know how this is meant to function).


Addendum:

I suspect the purpose of the above block is to assign integer keys to a new hash (something that is impossible otherwise). Seeing the later steps with the invert, this would mean that the final printed hash will have integer values, not strings.


It then adds two new key value pairs to the hash:

.merge({PaymentType::ACCOUNTCREDIT => I18n.t("customer.payment_types_billing.#{PaymentType::ACCOUNTCREDIT}", :amount => number_to_currency(get_account_credit))})

The first pair has a key equal to ACCOUNTCREDIT, with another value retrieved from the YAML. The second is the key :amount, with the value of "get_account_credit" (presumably a method with a decimal output) converted to currency for the current region.

As we reach the actual content of the payment_types method, the results from above (the newly-formed hash) is a block with a delete condition. If get_account_credit is returning a non-positive number, the ACCOUNTCREDIT keyed pair is deleted

.delete_if {|key, value|  (key == PaymentType::ACCOUNTCREDIT && get_account_credit <= 0) }

Finally, the hash is inverted (the keys become the values, and the values become the keys):

.invert

Upvotes: 3

Related Questions