Skip to content

Instantly share code, notes, and snippets.

@jamiehodge
Created November 22, 2013 12:38
Show Gist options
  • Save jamiehodge/7599237 to your computer and use it in GitHub Desktop.
Save jamiehodge/7599237 to your computer and use it in GitHub Desktop.
simple mapper
require_relative 'links'
require_relative 'tags'
module Foil
class File
attr_accessor :id,
:category_id, :license_id, :visibility_id,
:description, :name,
:annotations, :authors, :editors, :links, :publishers, :tags
def initialize(attributes)
@id = attributes['id']
@category_id = attributes['category_id']
@license_id = attributes['license_id']
@visibility_id = attributes['visibility_id']
@description = attributes['description']
@name = attributes['name']
@annotations = Array attributes['annotations']
@authors = Array attributes['authors']
@editors = Array attributes['editors']
@links = Array attributes['links']
@publishers = Array attributes['publishers']
@tags = Array attributes['tags']
end
def links
@links ||= Links.for_file(id)
end
def tags
@tags ||= Tags.for_file(id)
end
end
end
require_relative 'db'
require_relative 'file'
module Foil
class Files
include Enumerable
def initialize(db: Foil::DB.new, model: Foil::File)
@db = db
@model = model
prepare
end
def [](id)
@db.exec_prepared('find_file', [id])
.map {|r| @model.new(r) }
.first
end
def for_folder(id)
@db.exec_prepared('find_files_for_folder', [id])
.map {|r| @model.new(r) }
end
def each(&block)
@db.exec('SELECT * FROM files')
.lazy
.map {|attributes| @model.new(attributes)}
.each(&block)
end
def <<(i)
@db.exec_prepared('insert_file', values(i))
.map {|r| @model.new(r) }
.first
end
def []=(id, i)
@db.exec_prepared('update_file', [id] + values(i))
.map {|r| @model.new(r) }
.first
end
def -(f)
@db.exec_prepared('delete_file', [i.id])
instance
end
private
def prepare
@db.prepare('find_files_for_folder',
'SELECT f.id, f.name FROM files f JOIN filings fs ON (fs.file_id = f.id AND fs.folder_id = $1)')
@db.prepare('find_file',
'SELECT * FROM files WHERE id = $1')
@db.prepare('insert_file',
'INSERT INTO files (category_id, license_id, visibility_id, description, name) VALUES ($1, $2, $3, $4, $5) returning *')
@db.prepare('update_file',
'UPDATE files SET category_id=$2, license_id=$3, visibility_id=$4, description=$5, name=$6 WHERE id=$1 returning *')
@db.prepare('delete_file',
'DELETE FROM files WHERE id=$1')
end
def values(i)
[i.category_id, i.license_id, i.visibility_id,
i.description, i.name]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment