rails: serializable_hash 方法中 super 的用法 - cwy007/tips-and-skills GitHub Wiki
1. super 定义
From the (rather old) pickaxe book (AKA Programming Ruby
):
When you invoke super with no arguments, Ruby sends a message to the current object's parent, asking it to invoke a method of the same name as the current method, and passing it the parameters that were passed to the current method.
2. 示例
So given this:
class C
def m(x)
puts x
end
end
class D < C
def m(x)
super
end
end
D.new.m(6)
you'll see 6 because the x argument to D#m
is implicit in the super when you don't supply any explicit arguments for the parent version of m.
Add an argument to the MyTest#my_module_method
definition and you'll see something.
参考链接
问题来源
Rails, Angular, Postgres, and Bootstrap 2nd.pdf
class CustomerDetail < ApplicationRecord
self.primary_key = 'customer_id'
def cardholder_id
self.customer_id
end
def serializable_hash(options=nil)
super.merge({ cardholder_id: cardholder_id })
end
end
结果
visit: http://localhost:5000/customers/291313.json get the result
{
"customer": {
"customer_id": 291313,
"first_name": "Patrick",
"last_name": "Abshire",
"email": "[email protected]",
"username": "randi_hoppe291312",
"joined_at": "2018-01-14T15:43:19.900Z",
"billing_address_id": 1020114,
"billing_street": "23989 Durgan Turnpike",
"billing_city": "Port Destineeview",
"billing_state": "ID",
"billing_zipcode": "48203",
"shipping_address_id": 1020115,
"shipping_street": "6202 Wehner Estates",
"shipping_city": "Alenemouth",
"shipping_state": "ND",
"shipping_zipcode": "39826",
"cardholder_id": 291313
}
}