class LiteRecord::Base

Constants

DB

Attributes

table[RW]
attributes[R]

Public Class Methods

count() click to toggle source
# File lib/lite_record/base.rb, line 24
def count
  DB.get_first_value("SELECT count(id) from #{table}")
end
create(data) click to toggle source
# 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) click to toggle source
# File lib/lite_record/base.rb, line 20
def find(id)
  new(DB.get_first_row("SELECT * from #{table} where id = ?", id))
end
new(attributes) click to toggle source
# File lib/lite_record/base.rb, line 59
def initialize(attributes)
  @attributes = attributes
end

Private Class Methods

data_hash(data) click to toggle source
# File lib/lite_record/base.rb, line 38
def data_hash(data)
  keys.map { |k| [k, data[k]] }.to_h
end
keys() click to toggle source
# File lib/lite_record/base.rb, line 30
def keys
  @keys ||= table_columns - ['id']
end
sql_value(value) click to toggle source
# File lib/lite_record/base.rb, line 46
def sql_value(value)
  if value.nil?
    'null'
  elsif value.is_a?(String)
    "'#{value}'"
  else
    value
  end
end
sql_values(data) click to toggle source
# File lib/lite_record/base.rb, line 34
def sql_values(data)
  keys.map { |k| sql_value(data[k]) }
end
table_columns() click to toggle source
# File lib/lite_record/base.rb, line 42
def table_columns
  @table_columns ||= DB.table_info(table).map { |r| r['name'] }
end

Public Instance Methods

[](key) click to toggle source
# File lib/lite_record/base.rb, line 75
def [](key)
  attributes[key.to_s]
end
[]=(key, value) click to toggle source
# File lib/lite_record/base.rb, line 79
def []=(key, value)
  attributes[key.to_s] = value
end
destroy() click to toggle source
# File lib/lite_record/base.rb, line 71
def destroy
  DB.execute("DELETE FROM #{self.class.table} WHERE id = #{self['id']}")
end
save() click to toggle source
# 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

Private Instance Methods

update_fields() click to toggle source
# File lib/lite_record/base.rb, line 85
def update_fields
  attributes.map do |key, value|
    "#{key} = #{self.class.send(:sql_value, value)}"
  end.join(',')
end