Created
September 20, 2010 07:24
-
-
Save mackato/587534 to your computer and use it in GitHub Desktop.
ruby coredata access class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'sqlite3' | |
class Coredata | |
attr_accessor :db | |
def initialize(app_name) | |
pattern = File.join("#{ENV['HOME']}", | |
"/Library/Application Support/iPhone Simulator/*", | |
"/Applications/*/Documents/#{app_name}.sqlite") | |
match_paths = Dir.glob(pattern) | |
path = match_paths.size == 1 ? match_paths.first : nil | |
raise "Database '#{pattern}' not found." until path | |
@db = SQLite3::Database.new(path) | |
end | |
def close | |
db.close | |
end | |
def count(entity_name) | |
sql = "SELECT COUNT(*) FROM #{table_name(entity_name)}" | |
db.execute(sql).first.first | |
end | |
def insert(entity_name, params = {}) | |
fields = params.keys.map { |key| "z#{key}" }.join(', ') | |
placeholder = params.keys.map { |key| '?' }.join(', ') | |
sql = "INSERT INTO #{table_name(entity_name)} (Z_ENT, Z_OPT, #{fields}) VALUES (?, ?, #{placeholder})" | |
values = [1, 1] | |
values << params.values.map do |value| | |
value.respond_to?(:strftime) ? value.to_i - 978328800 : value | |
end | |
db.execute(sql, values) | |
end | |
def delete_all(entity_name) | |
sql = "DELETE FROM #{table_name(entity_name)}" | |
db.execute(sql) | |
end | |
private | |
def table_name(entity_name) | |
"Z#{entity_name.upcase}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment