1. Keyword delegate pada Model
Contoh kasus penggunaan keyword delegate
class University < ActiveRecord::Base
has_many :lecturers
end
class Lecturer < ActiveRecord::Base
belongs_to :university
end
[1] pry(main)> my_lecturer = Lecturer.find('459352183')
=> “Agung Supriadi”
[2] pry(main)> my_lecturer.university.abbreviated_name
=> “BINUS”
[9] pry(main)> my_lecturer.university.address
=> “Jl. Kebon Jeruk Raya No. 27, Kebon Jeruk”
Jika kita menggunakan keyword delegate, maka kita bisa mengakses lebih cepat:
class Lecturer < ApplicationRecord
belongs_to :university
delegate :abbreviated_name, :address, to: :university
end
[10] pry(main)> my_lecturer.abbreviated_name
=> “BINUS”
[11] pry(main)> my_lecturer.address
=> “Jl. Kebon Jeruk Raya No. 27, Kebon Jeruk”
Bagaimana jika my_lecturer pun punya address? maka kita bisa gunakan prefix pada delegate
class Lecturer < ApplicationRecord
belongs_to :university
delegate :abbreviated_name, :address, to: :university, prefix: true
def address
"this is address of the lecturer"
end
end
[21] pry(main)> my_lecturer.address
=> "this is address of the lecturer"
[22] pry(main)> my_lecturer.university_address
=> “Jl. Kebon Jeruk Raya No. 27, Kebon Jeruk”
Atau menggunakan custom prefix
class Lecturer < ApplicationRecord
belongs_to :university
delegate :abbreviated_name, :address, to: :university, prefix: :campus
def address
"this is address of the lecturer"
end
end
[22] pry(main)> my_lecturer.campus_address
=> “Jl. Kebon Jeruk Raya No. 27, Kebon Jeruk”