Class: LiteRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/lite_record/base.rb

Constant Summary collapse

DB =
LiteRecord.connection

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes) ⇒ Base

Returns a new instance of Base.



59
60
61
# File 'lib/lite_record/base.rb', line 59

def initialize(attributes)
  @attributes = attributes
end

Class Attribute Details

.tableObject

Returns the value of attribute table.



6
7
8
# File 'lib/lite_record/base.rb', line 6

def table
  @table
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



57
58
59
# File 'lib/lite_record/base.rb', line 57

def attributes
  @attributes
end

Class Method Details

.countObject



24
25
26
# File 'lib/lite_record/base.rb', line 24

def count
  DB.get_first_value("SELECT count(id) from #{table}")
end

.create(data) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/lite_record/base.rb', line 8

def create(data)
  data.delete('id')
  columns = keys.join(',')
  values = sql_values(data).join(',')

  DB.execute("INSERT into #{table}(#{columns}) values(#{values})")

  id = DB.get_first_value("SELECT last_insert_rowid() from #{table}")

  new(data_hash(data).merge('id' => id))
end

.find(id) ⇒ Object



20
21
22
# File 'lib/lite_record/base.rb', line 20

def find(id)
  new(DB.get_first_row("SELECT * from #{table} where id = ?", id))
end

Instance Method Details

#[](key) ⇒ Object



75
76
77
# File 'lib/lite_record/base.rb', line 75

def [](key)
  attributes[key.to_s]
end

#[]=(key, value) ⇒ Object



79
80
81
# File 'lib/lite_record/base.rb', line 79

def []=(key, value)
  attributes[key.to_s] = value
end

#destroyObject



71
72
73
# File 'lib/lite_record/base.rb', line 71

def destroy
  DB.execute("DELETE FROM #{self.class.table} WHERE id = #{self['id']}")
end

#saveObject



63
64
65
66
67
68
69
# File 'lib/lite_record/base.rb', line 63

def save
  return self.class.create(attributes) if self['id'].nil?
  
  DB.execute("UPDATE #{self.class.table} SET #{update_fields} WHERE id = #{self['id']}")
  
  true
end