Created
December 30, 2018 23:17
-
-
Save zgfif/f687682816f07a7af930b3400d09dfde 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 | |
@@total = [] | |
attr_reader :name, :age | |
def initialize name, age | |
@name = name | |
@age = age | |
end | |
class << self | |
def create name:, age: | |
obj = new name, age | |
@@total << obj | |
obj | |
end | |
def all | |
@@total | |
end | |
def find_by **args | |
all.select { |element| element if condition element, **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: { integer: true, greater_than: 0 } | |
validate :duplicate_names | |
def duplicate_names | |
all_names = Superhero.all.collect {|elem| elem.name} | |
if all_names.count(name) >= 2 | |
errors.add(:name, "#{name} is already exists") | |
end | |
end | |
end | |
superhero1 = Superhero.create name: 'Jessy', age: 54 | |
p superhero1.valid? | |
p superhero1.errors.messages | |
superhero2 = Superhero.create name: 'John McClane', age: 12 | |
p superhero2.valid? | |
p superhero2.errors.messages | |
superhero3 = Superhero.create name: 'John McClane', age: 0 | |
p superhero3.valid? | |
p superhero3.errors.messages | |
# p Superhero.all | |
# p Superhero.find_by name: 'John McClane', age: 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment