Last active
December 19, 2015 22:19
-
-
Save anthonylewis/6026693 to your computer and use it in GitHub Desktop.
An example using method_missing to add user features
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
require 'set' | |
class User | |
def initialize | |
@features = Set.new | |
end | |
def method_missing(meth, *args) | |
if meth.to_s =~ /^can_(.*)\?$/ | |
@features.include? $1.to_s | |
elsif meth.to_s =~ /^can_(.*)$/ | |
@features << $1.to_s | |
self | |
else | |
super | |
end | |
end | |
def respond_to?(meth) | |
if meth.to_s =~ /^can_(.*)\?$/ | |
true | |
elsif meth.to_s =~ /^can_(.*)$/ | |
true | |
else | |
super | |
end | |
end | |
end | |
u = User.new | |
u.can_code | |
puts u.can_code? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment