Skip to content

Instantly share code, notes, and snippets.

@teslur teslur/my_dynamic_finders.rb Secret
Last active Aug 27, 2019

Embed
What would you like to do?
reimplement_dynamic_finders
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
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
You can’t perform that action at this time.