tôi sử dụng này cho phép "thân thiện" tên trong một bảng Dưa chuột được phân tách thành lớp thuộc tính như vậy mà Factory Girl có thể tạo ra một thể hiện:
Given(/^an organization exists with the following attributes:$/) do |table|
# Build a mapping from the "friendly" text in the test to the lower_case actual name in the class
map_to_keys = Hash.new
table.transpose.hashes.first.keys.each { |x| map_to_keys[x] = x.downcase.gsub(' ', '_') }
table.transpose.hashes.each do |obj|
obj.keys.each { |k| obj[map_to_keys[k]] = obj.delete(k) if map_to_keys[k] }
create(:organization, Rack::Utils.parse_nested_query(obj.to_query))
end
end
Đối với những gì nó có giá trị, bảng Dưa chuột trông như thế này :
Background:
And an organization exists with the following attributes:
| Name | Example Org |
| Subdomain | xfdc |
| Phone Number | 123-123-1234 |
| Address | 123 E Walnut St, Anytown, PA 18999 |
| Billing Contact | Alexander Hamilton |
| Billing Address | 123 E Walnut St, Anytown, PA 18999 |
Và map_to_keys
trông như thế này:
{
"Name" => "name",
"Subdomain" => "subdomain",
"Phone Number" => "phone_number",
"Address" => "address",
"Billing Contact" => "billing_contact",
"Billing Address" => "billing_address"
}
Nguồn
2015-01-04 14:59:28
Cảm ơn, điều này thật tuyệt! Bây giờ, nếu tôi chỉ muốn thay đổi một số tên khóa, có cách nào để kiểm tra nếu ánh xạ tồn tại cho khóa không? – Chanpory
Chỉ cần sử dụng 'ánh xạ [k] || k' thay vì 'ánh xạ [k]' ở trên và nó sẽ để lại các phím không có trong ánh xạ. –
Rực rỡ! THanks rất nhiều :-) – Chanpory