Skip to content

Instantly share code, notes, and snippets.

@JamesAndresCM
Last active February 4, 2020 18:24
Show Gist options
  • Save JamesAndresCM/9ee12fda43ef15485a279326a62305c2 to your computer and use it in GitHub Desktop.
Save JamesAndresCM/9ee12fda43ef15485a279326a62305c2 to your computer and use it in GitHub Desktop.
class Base
include ActiveModel::Model
extend ActiveModel::Callbacks
attr_accessor :id
# https://stackoverflow.com/questions/17681789/rails-what-is-a-proper-way-to-include-callbacks-into-tableless-model
define_model_callbacks :save, :create
ALL = []
def initialize(params = {})
run_callbacks :create do
super
end
end
class << self
def first
all.first
end
def last
all.last
end
def all
ALL.select{|el| el.is_a?(self) }
end
def create(params = {})
model = self.new(params)
model.save
model
end
def delete(object)
all.reject!{|el| el.id.eql?(object) }
all.each do |el|
r_el = el.id.eql?(object)
all.delete_at(all.index{|x| x.id.eql? object }) if r_el
end
end
def update(object, params = {})
el = all.detect{|el| el.id.eql?(object)}
el.update_record(params) if el
end
end
def persisted?
id ? true : false
end
def attributes
instance_variables.map{|el| [el.to_s.tr('@',''), instance_variable_get(el.to_s)] }.to_h
end
def save
run_callbacks :save do
return false unless valid?
add if id.nil?
true
end
end
def add
@id = self.class.all.size + 1
ALL << self
end
def update_record(params)
self.attributes = params
save
end
end
class Account < Base
include ActiveModel::Validations::Callbacks
validates :name, :email, :country, :language, :timezone, presence: true
validates_inclusion_of :language, in: ['en','es']
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, allow_blank: true
ATTRS = %i[name email country language timezone id]
attr_accessor(*ATTRS)
class << self
ATTRS.each do |key|
define_method("find_by_#{key}") do |arg|
all.select{|el| el.send(key).eql?(arg) }
end
end
end
def users
User.all.select{|el| el.account_id.eql?(id) }
end
end
class User < Base
include ActiveModel::Validations::Callbacks
validates :name, :email, :account_id, presence: true
ATTRS = %i[name email account_id]
attr_accessor(*ATTRS)
before_save :valid_account
def valid_account
raise Exception.new 'Account must be exists' if Account.find_by_id(account_id).empty?
end
def account
Account.find_by_id(account_id)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment