Created
March 13, 2020 15:56
-
-
Save sunny/ac43e460c9265cb6a041c10020a266df to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# frozen_string_literal: true | |
module Finder | |
attr_reader :id | |
def initialize(**) | |
@id = self.class.count | |
end | |
def self.included(base) | |
base.extend(ClassMethods) | |
end | |
module ClassMethods | |
def find(id) | |
scope.find { |car| car.id == id } | |
end | |
def all | |
scope.to_a | |
end | |
def find_by(attribute, value) | |
scope.find { |car| car.public_send(attribute) == value } | |
end | |
def method_missing(name, *arguments) | |
if name.to_s =~ /^find_by_(.*?)$/ | |
find_by($1, arguments.first) | |
else | |
super | |
end | |
end | |
def count | |
scope.count | |
end | |
def scope | |
ObjectSpace.each_object(self) | |
end | |
end | |
end | |
class Car | |
include Finder | |
def initialize(motor:) | |
@motor = motor | |
super | |
end | |
attr_reader :motor | |
end | |
first_car = Car.new(motor: "diesel") | |
second_car = Car.new(motor: "gazoline") | |
third_car = Car.new(motor: "electric") | |
p first_car.id | |
p second_car.id | |
p third_car.id | |
p Car.count | |
p Car.find(2) | |
p Car.all | |
p Car.find_by_motor("diesel") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment