/dao/account_dao.rb
Ruby | 70 lines | 45 code | 8 blank | 17 comment | 3 complexity | f9203314afde2190a306e38154f70298 MD5 | raw file
- # 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