-
-
Save workmaster2n/8690657 to your computer and use it in GitHub Desktop.
| class TweetToTheWorld < Struct.new(:person) | |
| extend Forwardable | |
| #def delegators :person, :twitter_handle, :name | |
| delegate :twitter_hande, to: :person | |
| delegate :name, to: :person | |
| def call | |
| Tweetirific.tweet(handle, twitter_message) | |
| end | |
| private | |
| def twitter_message | |
| "#{name} is Totes McGoats a hottie" | |
| end | |
| end |
By default, ActiveSupport::Delegation is added to Module… so every single class and module in your rails app will have the delegate method defined from active support. That's either awesome, or scary, depending on your perspective.
I prefer to use Forwardable so that I can test things like this without loading rails (or even active support).
Also, active support delegate allows you to return nil or blank if the related object is nil. that could be good, or could be bad, for example because it hides a nil object which should actually raise an error and point out a problem in your design or setup.
Active support does have a nice prefix option which will allow you to make methods that declare their source… but this also somewhat reveals the implementation.
You're thinking of ActiveModel's delegator here... but it's the same concept but in a way that has no reliance on ActiveRecord/ActiveModel.