Last active
December 29, 2018 20:57
-
-
Save zgfif/5b4e6e059572f8f895ff1e95e3deba1f to your computer and use it in GitHub Desktop.
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 'active_model' | |
class Superhero | |
include ActiveModel::Validations | |
attr_accessor :name, :age | |
def initialize **args | |
@name = args[:name] | |
@age = args[:age] | |
end | |
class << self | |
def create **args | |
new **args | |
end | |
def all | |
ObjectSpace.each_object(self).to_a | |
end | |
def find_by **args | |
all.select { |elem| elem if condition elem, **args } | |
end | |
def condition elem, **args | |
if args[:name] && args[:age] | |
elem.name == args[:name] && elem.age == args[:age] | |
elsif args[:name] | |
elem.name == args[:name] | |
elsif args[:age] | |
elem.age == args[:age] | |
end | |
end | |
end | |
validates :age, numericality: { only_integer: true, greater_than: 0 }, allow_nil: true | |
validate :name_must_be_unique | |
def name_must_be_unique | |
if all_names.count(name) >= 2 | |
errors.add(:name, "the name: #{name} is already exists." ) | |
end | |
end | |
def all_names | |
Superhero.all.map { |e| e.name } | |
end | |
end | |
superhero1 = Superhero.create name: 'Bruce', age: 2 | |
# p superhero1.valid? | |
# p superhero1.errors.messages | |
superhero2 = Superhero.create name: 'Bruce', age: 0 | |
p superhero2.valid? | |
superhero3 = Superhero.create name: 'David', age: 21 | |
superhero4 = Superhero.create name: 'James', age: 10 | |
superhero5 = Superhero.create name: 'Bruce', age: 13 | |
# p superhero5.valid? | |
# p superhero5.errors.messages | |
p Superhero.find_by name: 'Bruce' | |
# p Superhero.find_by age: 21 | |
# p Superhero.find_by name: 'James', age: 12 | |
# p superhero1.valid? | |
# p superhero1.errors.messages |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment