Skip to content

Instantly share code, notes, and snippets.

@zgfif
Last active December 29, 2018 20:57
Show Gist options
  • Save zgfif/5b4e6e059572f8f895ff1e95e3deba1f to your computer and use it in GitHub Desktop.
Save zgfif/5b4e6e059572f8f895ff1e95e3deba1f to your computer and use it in GitHub Desktop.
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