class EasyMvc::Mapper

Public Class Methods

find(id) click to toggle source
# File lib/easymvc/mapper.rb, line 56
def self.find(id)
  row = @@db.execute("SELECT #{@@mapping.keys.join(",")} FROM #{@@table_name} WHERE id=?", id).first
  self.map_row_to_object(row)
end
find_all() click to toggle source
# File lib/easymvc/mapper.rb, line 70
def self.find_all
  data = @@db.execute "SELECT #{@@mapping.keys.join(",")} FROM #{@@table_name}"
  data.map do |row|
    self.map_row_to_object(row)
  end
end
map_row_to_object(row) click to toggle source
# File lib/easymvc/mapper.rb, line 61
def self.map_row_to_object(row)
  model = @@model.new

  @@mapping.each_value.with_index do |attribute, index|
    model.send "#{attribute}=", row[index]
  end
  model
end

Public Instance Methods

delete(id) click to toggle source
# File lib/easymvc/mapper.rb, line 77
def delete(id)
  @@db.execute "DELETE FROM #{@@table_name} WHERE id=?", id
end
get_columns() click to toggle source
# File lib/easymvc/mapper.rb, line 38
def get_columns
  column = @@mapping.keys
  column.delete(:id)
  column.join(",")
end
get_values() click to toggle source
# File lib/easymvc/mapper.rb, line 32
def get_values
  attributes = @@mapping.values
  attributes.delete(:id)
  attributes.map { |method| self.send(method) }
end
method_missing(method, *args) click to toggle source
# File lib/easymvc/mapper.rb, line 52
def method_missing(method, *args)
  @model.send method
end
new_record_placeholders() click to toggle source
# File lib/easymvc/mapper.rb, line 22
def new_record_placeholders
  (["?"] * (@@mapping.size - 1)).join(",")
end
new_record_values() click to toggle source
# File lib/easymvc/mapper.rb, line 48
def new_record_values
  get_values
end
save(model) click to toggle source
# File lib/easymvc/mapper.rb, line 10
def save(model)
  @model = model
  if model.id
    @@db.execute %Q(
      UPDATE #{@@table_name}
      SET #{update_record_placeholders}
      where id = ?), update_record_values
  else
    @@db.execute "INSERT INTO #{@@table_name} (#{get_columns}) VALUES (#{new_record_placeholders})", new_record_values
  end
end
update_record_placeholders() click to toggle source
# File lib/easymvc/mapper.rb, line 26
def update_record_placeholders
  column = @@mapping.keys
  column.delete(:id)
  column.map { |col| "#{col}=?" }.join(",")
end
update_record_values() click to toggle source
# File lib/easymvc/mapper.rb, line 44
def update_record_values
  get_values << self.send(:id)
end