mycash /dao/account_dao.rb

Language Ruby Lines 71
MD5 Hash f9203314afde2190a306e38154f70298
Repository https://bitbucket.org/jjhop/mycash View Raw File
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright: (C) 2004-2010 Rafal Kotusiewicz aka 'jjhop'. All rights reserved.
#
# http://bitbucket.org/jjhop/mycash/overview/
# http://bitbucket.org/jjhop/mycash/wiki/Home
#

require 'rubygems'
require File.join(File.dirname(__FILE__), '../model/account')

module MyCashDAO

  class AccountDAO
    def initialize(dbh)
      @dbh = dbh
    end
    
    def find_by_id(id)
      begin
        r = @dbh.get_first_row("SELECT * FROM accounts WHERE id=:id", 'id' => id)
        MyCashModel::Account.create_from_hash(r)
      rescue Exception => ex
        raise DAOException, ex
      end
    end

    def get_all
      result = []
      begin
        @dbh.execute("SELECT * FROM accounts ORDER by created_at ASC") do |r|
          result<< MyCashModel::Account.create_from_hash(r)
        end
      rescue Exception => ex
        raise DAOException, ex
      end
      result
    end
    
    def save_or_update(account)
      unless MyCashModel::Account == account.class
        raise DAOException, 
          'Argumentem metody MyCashDAO::AccountDAO#save_or_update musi' +
          ' być prawidłowy obiekt klasy MyCashModel::Account'
      end
        
      if account.new?
        @dbh.execute(
          "INSERT INTO accounts(id, created_at, name) VALUES(?,?,?)",
          nil, account.created_at || Time.new, account.name)
      else
        @dbh.execute( "UPDATE accounts SET name=? WHERE id=?", account.name, account.account_id)
      end
    end
    
    def delete_by_id(id)
      @dbh.execute("DELETE FROM accounts WHERE id=:id", 'id' => id)
    end
  end
end
Back to Top