-
-
Save teslur/1ae570cfdf6eb639003b4f9ddd2f3843 to your computer and use it in GitHub Desktop.
reimplement_dynamic_finders
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
module MyDynamicFinders | |
private | |
def method_missing(symbol, *arg, &block) | |
if symbol.to_s.start_with?('find_by_') | |
sym_str = symbol.to_s.end_with?('!') ? symbol.to_s.chop : symbol.to_s | |
conds = sym_str.gsub!(/find_by_/, '').split('_and_').zip(arg) | |
ret = $DATABASE.find do |user| | |
conds.inject(true) do |acc, cond| | |
acc && ( user.public_send("#{cond[0]}".to_sym) == cond[1] ) | |
end | |
end | |
symbol.to_s.end_with?('!') ? ( ret || raise ) : ret | |
else | |
super | |
end | |
end | |
def respond_to_missing?(symbol, *arg) | |
if symbol.to_s.start_with?('find_by_') | |
true | |
else | |
super | |
end | |
end | |
end |
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
module MyDynamicFinders | |
private | |
def method_missing(symbol, *arg, &block) | |
if symbol.to_s.start_with?('find_by_') | |
sym_str = symbol.to_s.end_with?('!') ? symbol.to_s.chop : symbol.to_s | |
conds = sym_str.gsub!(/find_by_/, '').split('_and_').zip(arg) | |
ret = $DATABASE.find do |user| | |
conds.all? do |attr, value| | |
user.public_send("#{attr}".to_sym) == value | |
end | |
end | |
symbol.to_s.end_with?('!') ? ( ret || raise ) : ret | |
else | |
super | |
end | |
end | |
def respond_to_missing?(symbol, *arg) | |
if symbol.to_s.start_with?('find_by_') | |
true | |
else | |
super | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment