class Rhino::Model::SQLite

Public Class Methods

all() click to toggle source
# File lib/rhino/sqlite_model.rb, line 34
def self.all
  rows = DB.execute("SELECT #{schema.keys.join(',')} from #{table};")
  rows.map {|row| mapping_data row }
end
count() click to toggle source
# File lib/rhino/sqlite_model.rb, line 91
def self.count
  DB.execute("SELECT COUNT(*) FROM #{table}")[0][0]
end
create(values) click to toggle source
# File lib/rhino/sqlite_model.rb, line 51
def self.create(values)
  values.delete "id"
  keys = schema.keys - ['id']
  vals =  keys.map do |key|
    values[key] ? to_sql(values[key]) : "NULL"
  end
  DB.execute "INSERT INTO #{table} (#{keys.join ","}) VALUES (#{vals.join ","});"

  data = Hash[keys.zip vals]
  sql = "SELECT last_insert_rowid();"
  data["id"] = DB.execute(sql)[0][0]
  self.new data
end
delete(id) click to toggle source
# File lib/rhino/sqlite_model.rb, line 86
def self.delete(id)
  DB.execute("DELETE FROM #{table} WHERE id = #{id.to_i}")
  true
end
find(id) click to toggle source
# File lib/rhino/sqlite_model.rb, line 27
def self.find(id)
  row = DB.execute("
    SELECT #{schema.keys.join(',')} from #{table} where id = #{id};
  ")
  mapping_data row[0]
end
mapping_data(row_data) click to toggle source
# File lib/rhino/sqlite_model.rb, line 47
def self.mapping_data(row_data)
  self.new Hash[schema.keys.zip row_data]
end
new(data = {}) click to toggle source
# File lib/rhino/sqlite_model.rb, line 12
def initialize(data = {})
  @hash = data
end
schema() click to toggle source
# File lib/rhino/sqlite_model.rb, line 99
def self.schema
  return @schema if @schema
  @schema = {}
  DB.table_info(table) do |row|
    @schema[row["name"]] = row["type"]
  end
  @schema
end
table() click to toggle source
# File lib/rhino/sqlite_model.rb, line 95
def self.table
  Rhino.to_underscore name
end
to_sql(val) click to toggle source
# File lib/rhino/sqlite_model.rb, line 16
def self.to_sql(val)
  case val
  when Numeric
    val.to_s
  when String
    "'#{val}'"
  else
    raise "Can't change #{val.class} to SQL"
  end
end

Public Instance Methods

[](name) click to toggle source
# File lib/rhino/sqlite_model.rb, line 39
def [](name)
  @hash[name.to_s]
end
[]=(name, value) click to toggle source
# File lib/rhino/sqlite_model.rb, line 43
def []=(name, value)
  @hash[name.to_s] = value
end
save() click to toggle source
# File lib/rhino/sqlite_model.rb, line 82
def save
  self.save!  rescue false
end
save!() click to toggle source
# File lib/rhino/sqlite_model.rb, line 65
def save!
  unless @hash["id"]
    self.class.create @hash
    return true
  end
  fields = @hash.map do |k,v|
    "#{k}=#{self.class.to_sql(v)}"
  end.join(",")

  DB.execute ("
    UPDATE #{self.class.table}
    SET #{fields}
    WHERE id = #{@hash['id']}
  ")
  true
end