Skip to content

Instantly share code, notes, and snippets.

@mdespuits
Last active December 12, 2015 04:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdespuits/4715262 to your computer and use it in GitHub Desktop.
Save mdespuits/4715262 to your computer and use it in GitHub Desktop.
Example of a basic decorator that uses `method_missing` rather than Delegation
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