Sha256: 1cdb0c93779f7152e147be89fbd8ff3b0738095821e0a7c3b10e776380c462fc

Contents?: true

Size: 1.95 KB

Versions: 2

Compression:

Stored size: 1.95 KB

Contents

require_relative 'DBUniversity'
require 'json'
require 'sqlite3'
class StudentListDBAdapter

  def initialize
    self.client = DBUniversity.instance
  end

  #last_name, first_name, paternal_name, phone, telegram, email, git
  def into_hash(arr)
    attrs = {}
    i=0
    %i[id last_name first_name paternal_name phone telegram email git].each do |attr|
      attrs[attr] = arr[i] unless arr[i].nil?
      i=i+1
    end
    attrs
  end
  def student_by_id(id_student)
    hash = client.prepare_exec('SELECT * FROM students WHERE id = ?', id_student).first
    hash=into_hash(hash)
    return nil if hash.nil?

    Student.new(**hash)
  end

  def get_k_n_student_short_list(k,n,data_list=nil )
    offset = (k - 1) * n
    students = client.prepare_exec('SELECT * FROM students LIMIT ?, ?', offset, n)
    slice = students.map { |h|
      h = h.transform_keys(&:to_sym)
      StudentShort.new(Student.into_hash(h))
    }
    return DataListStudentShort.new(slice) if data_list.nil?

    data_list.replace_objects(slice)
    data_list
  end

  def add_student(student)
    st = client.prepare_exec('insert into students (last_name, first_name, paternal_name, phone,
                          telegram, email, git) VALUES (?, ?, ?, ?, ?, ?, ?)',*student_attr(student))
  end

  def replace_student(id_student, student)
    st ='UPDATE students SET last_name=?, first_name=?, paternal_name=?, phone=?, telegram=?, email=?, git=? WHERE id=?'
    client.prepare_exec(st,*student_attr(student), id_student)
  end

  def delete_student(id_student)
    client.prepare_exec('DELETE FROM students WHERE id = ?', id_student)
  end

  def count_student
    client.query('SELECT COUNT(id) FROM students').next[0]
  end

  private

  attr_accessor :client

  def student_attr(student)
    [student.last_name, student.first_name, student.paternal_name,
     student.phone, student.telegram,
     student.email, student.git]
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rafmycat-1.0.1 lib/source/Students_list_DB.rb
rafmycat-1.0.0 lib/source/Students_list_DB.rb