module Persistence::ClassMethods

Public Instance Methods

create(attrs) click to toggle source
# 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.map {|x| '?'}.join(', ')})",
    vals
  )

  data = Hash[attributes.zip attrs.values]
  data["id"] = connection.execute("SELECT last_insert_rowid();")[0][0]
  new(data)
end
destroy(*id) click to toggle source
# File lib/bloc_record/persistence.rb, line 50
    def destroy(*id)
      if id.length > 1
        where_clause = "WHERE id IN (#{id.join(",")});"
      else
        where_clause = "WHERE id = #{id.first};"
      end

      connection.execute <<-SQL
        DELETE FROM #{table} #{where_clause}
      SQL

      true
    end
destroy_all(conditions_hash=nil) click to toggle source
# File lib/bloc_record/persistence.rb, line 64
    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 <<-SQL
          DELETE FROM #{table}
        SQL
      end

      true
    end
update(ids, updates) click to toggle source
# File lib/bloc_record/persistence.rb, line 26
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) click to toggle source
# File lib/bloc_record/persistence.rb, line 46
def update_all(updates)
  update(nil, updates)
end