Skip to content

Instantly share code, notes, and snippets.

@tlux
Created March 3, 2015 20:57
Show Gist options
  • Select an option

  • Save tlux/24fcbf71dc84cbb14a2b to your computer and use it in GitHub Desktop.

Select an option

Save tlux/24fcbf71dc84cbb14a2b to your computer and use it in GitHub Desktop.
ActiveRecord like finders for Arrays
class Array
def find_by!(attributes)
find_by(attributes) || fail('No element found')
end
def find_by(attributes)
detect do |item|
attributes.collect do |key, value|
item.public_send(key) == value
end.reduce(:&)
end
end
def where(attributes)
select do |item|
attributes.collect do |key, value|
item.public_send(key) == value
end.reduce(:&)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment