forked from owningrails/patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
not_active_record.rb
50 lines (40 loc) · 1013 Bytes
/
not_active_record.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
require "connection_adapter"
require "active_model"
module NotActiveRecord
class Base
include ActiveModel::Validations
@@connection = SqliteAdapter.new
def initialize(attributes={})
@attributes = attributes
end
def method_missing(name, *args)
if self.class.columns.include?(name)
@attributes[name]
else
super
end
end
def self.find(id)
find_by_sql("SELECT * FROM #{table_name} WHERE id = #{id.to_i} LIMIT 1").first
end
def self.all
find_by_sql("SELECT * FROM #{table_name}")
end
def self.find_by_sql(sql)
rows = @@connection.execute(sql)
rows.map do |values| # [1, 'Marc']
attributes = map_values_to_columns(values)
new(attributes)
end
end
def self.map_values_to_columns(values)
Hash[columns.zip(values)]
end
def self.columns
@@connection.columns(table_name)
end
def self.table_name
name.downcase + 's' # "users"
end
end
end