Skip to content

Instantly share code, notes, and snippets.

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