Module: Persistence::ClassMethods

Defined in:
lib/bloc_record/persistence.rb

Instance Method Summary collapse

Instance Method Details

#create(attrs) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/bloc_record/persistence.rb', line 10

def create(attrs)
  attrs = BlocRecord::Utility.convert_keys(attrs)
  attrs.delete "id"
  vals = attributes.map { |key| BlocRecord::Utility.sql_strings(attrs[key]) }

  connection.execute(
    "INSERT INTO #{table} (#{attributes.join(",")}) VALUES (?)",
    vals.join(",")
  )

  data = Hash[attributes.zip attrs.values]
  data["id"] = connection.execute("SELECT last_insert_rowid();")[0][0]
  new(data)
end

#destroy(*id) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/bloc_record/persistence.rb', line 49

def destroy(*id)
  if id.length > 1
    where_clause = "WHERE id IN (#{id.join(",")});"
  else
    where_clause = "WHERE id = #{id.first};"
  end

  connection.execute "    DELETE FROM \#{table} \#{where_clause}\n  SQL\n\n  true\nend\n"

#destroy_all(conditions_hash = nil) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/bloc_record/persistence.rb', line 63

def destroy_all(conditions_hash=nil)
  if conditions_hash && !conditions_hash.empty?
    conditions_hash = BlocRecord::Utility.convert_keys(conditions_hash)
    conditions = conditions_hash.keys.map { |key| "#{key} = ?" }.join(" and ")

    connection.execute(
      "DELETE FROM #{table} WHERE #{conditions};",
      conditions_hash.values
    )
  else
    connection.execute "      DELETE FROM \#{table}\n    SQL\n  end\n\n  true\nend\n"

#update(ids, updates) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/bloc_record/persistence.rb', line 25

def update(ids, updates)
  updates = BlocRecord::Utility.convert_keys(updates)
  updates.delete "id"
  updates_array = updates.keys.map { |key| "#{key} = ?" }
  if ids.class == Fixnum
    where_clause = "WHERE id = #{ids};"
  elsif ids.class == Array
    where_clause = ids.empty? ? ";" : "WHERE id IN (#{ids.join(",")});"
  else
    where_clause = ";"
  end

  connection.execute(
    "UPDATE #{table} SET #{updates_array.join(", ")} #{where_clause}",
    updates.values
  )

  true
end

#update_all(updates) ⇒ Object



45
46
47
# File 'lib/bloc_record/persistence.rb', line 45

def update_all(updates)
  update(nil, updates)
end