Class: RecordxSqlite

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

Instance Method Summary collapse

Constructor Details

#initialize(dbfile, table: '', primary_key: :id, pk: primary_key, sql: nil) ⇒ RecordxSqlite

Returns a new instance of RecordxSqlite.



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
# File 'lib/recordx_sqlite.rb', line 11

def initialize(dbfile, table: '', primary_key: :id, pk: primary_key, 
               sql: nil)
      
  @db = SQLite3::Database.new dbfile

  @db.results_as_hash = true
  
  if table.is_a? String then
    
    @table, @primary_key = table, pk.to_sym
    
  elsif table.is_a? Hash 
    
    h = table
    @table = h.keys.first
    @primary_key = h[@table].keys.first
    
    create_table(@table, h[@table]) if @db.table_info(@table).empty?
          
  end
  
  @sql =  sql || 'select * from ' + @table.to_s
  
  @a = nil
  
end

Instance Method Details

#allObject

note: when using method all() you will need to call method refresh() first if a record had recently been added since the recordset was loaded



41
42
43
44
# File 'lib/recordx_sqlite.rb', line 41

def all()    
  query(@sql) unless @a
  @a
end

#create(h = {}) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/recordx_sqlite.rb', line 46

def create(h={})
  
  fields = h.keys
  values = h.values

  sql = "INSERT INTO #{@table} (#{fields.join(', ')})
  VALUES (#{(['?'] * fields.length).join(', ')})"

  @db.execute(sql, values)
  
   :create
end

#delete(id) ⇒ Object



59
60
61
62
63
64
65
# File 'lib/recordx_sqlite.rb', line 59

def delete(id)
  
  sql = "DELETE FROM #{@table} WHERE #{@primary_key}='#{id}'"
  @db.execute sql
  
  :delete
end

#find(id) ⇒ Object



67
68
69
70
71
72
# File 'lib/recordx_sqlite.rb', line 67

def find(id)

  query(@sql) unless @a
  @a.find {|x| x.method(@primary_key).call == id}
  
end

#query(sql = @sql) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
# File 'lib/recordx_sqlite.rb', line 74

def query(sql=@sql)
  
  @sql = sql
  rs = @db.query sql
  
  @a = rs.map do |h| 
    h2 = h.inject({}) {|r, x| k, v = x; r.merge(k.to_sym => v)}
    RecordX.new(h2, self, h2[@primary_key]) 
  end    
  
end

#refreshObject



86
87
88
89
# File 'lib/recordx_sqlite.rb', line 86

def refresh()
  query(@sql)
  'refreshed'
end

#update(id, h = {}) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/recordx_sqlite.rb', line 91

def update(id, h={})

  col, value = h.to_a.first
  return if col == @primary_key

s = "
UPDATE #{@table}
SET #{col}='#{value}'
WHERE #{@primary_key.to_s}='#{id}';"

  @db.execute(s)

end