delegate - khanhld
TRANSCRIPT
![Page 1: Delegate - KhanhLD](https://reader036.vdocuments.us/reader036/viewer/2022082808/5551a17eb4c905013a8b5075/html5/thumbnails/1.jpg)
Delegatein Ruby on Rails
![Page 2: Delegate - KhanhLD](https://reader036.vdocuments.us/reader036/viewer/2022082808/5551a17eb4c905013a8b5075/html5/thumbnails/2.jpg)
● Delegate● Options● Demo
![Page 3: Delegate - KhanhLD](https://reader036.vdocuments.us/reader036/viewer/2022082808/5551a17eb4c905013a8b5075/html5/thumbnails/3.jpg)
Delegate
● Easily expose contained objects’ public methods as your own.
● Useful with ActiveRecord associations● delegate :method_name, to: :target
![Page 4: Delegate - KhanhLD](https://reader036.vdocuments.us/reader036/viewer/2022082808/5551a17eb4c905013a8b5075/html5/thumbnails/4.jpg)
Delegate
● Multiple delegates to the same target are allowed
● delegate :method1, :method2, to: :target● Methods can be delegated to instance
variables, class variables, or constants
![Page 5: Delegate - KhanhLD](https://reader036.vdocuments.us/reader036/viewer/2022082808/5551a17eb4c905013a8b5075/html5/thumbnails/5.jpg)
Delegate
● Delegate a method to the class by using :class
● delegate :hello, to: :class
![Page 6: Delegate - KhanhLD](https://reader036.vdocuments.us/reader036/viewer/2022082808/5551a17eb4c905013a8b5075/html5/thumbnails/6.jpg)
Options
● :allow_nil● If the target is nil and does not respond to
the delegated method a NoMethodError is raised
● delegate :name, to: :profile, allow_nil: true● Returns nil
![Page 7: Delegate - KhanhLD](https://reader036.vdocuments.us/reader036/viewer/2022082808/5551a17eb4c905013a8b5075/html5/thumbnails/7.jpg)
Options
● delegate :name, to: :profile, prefix: true● Delegate methods are prefixed with the
name of the object being delegated to.● delegate :name, to: :client, prefix: :customer● Supply a custom prefix
![Page 8: Delegate - KhanhLD](https://reader036.vdocuments.us/reader036/viewer/2022082808/5551a17eb4c905013a8b5075/html5/thumbnails/8.jpg)
Thank you