Last active
December 12, 2015 04:38
-
-
Save mdespuits/4715262 to your computer and use it in GitHub Desktop.
Example of a basic decorator that uses `method_missing` rather than Delegation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AccountDecorator | |
attr_accessor :account | |
def initialize(account) | |
@account = account | |
end | |
def method_missing(method_name, *args, &blk) | |
if account.respond_to?(method_name) | |
account_method_result(method_name, *args, &blk) | |
else | |
super | |
end | |
end | |
def respond_to_missing?(method_name) | |
attributes.include?(method_name.to_s) || super | |
end | |
def attributes | |
account.class.columns.map(&:name).map(&:to_s) | |
end | |
private | |
def account_method_result(method_name, *args, &blk) | |
if attributes.include?(method_name) | |
result = account.public_send(method_name, *args, &blk) | |
result.blank? ? '(none given)' : result | |
else | |
nil | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment