Skip to content

Instantly share code, notes, and snippets.

@kimh
Created October 29, 2014 13:58
Show Gist options
  • Save kimh/63462fa28c3a75fdeaf6 to your computer and use it in GitHub Desktop.
Save kimh/63462fa28c3a75fdeaf6 to your computer and use it in GitHub Desktop.
Codes that demonstrates ArticleRepository.adapter is nil
require 'bundler/setup'
require 'sqlite3'
require 'lotus/model'
require 'lotus/model/adapters/sql_adapter'
connection_uri = "sqlite://#{ __dir__ }/test.db"
database = Sequel.connect(connection_uri)
database.create_table! :authors do
primary_key :id
String :name
end
database.create_table! :articles do
primary_key :id
Integer :author_id, null: false
String :title
Integer :comments_count, default: 0
Boolean :published, default: false
end
Author = Struct.new(:id, :name) do
def initialize(attributes = {})
@id, @name = attributes.values_at(:id, :name)
end
end
class Article
include Lotus::Entity
self.attributes = :author_id, :title, :comments_count, :published # id is implicit
def published?
!!published
end
def publish!
@published = true
end
end
class AuthorRepository
include Lotus::Repository
end
class ArticleRepository
include Lotus::Repository
def self.most_recent_by_author(author, limit = 8)
query do
where(author_id: author.id).
desc(:id).
limit(limit)
end
end
def self.most_recent_published_by_author(author, limit = 8)
most_recent_by_author(author, limit).published
end
def self.published
query do
where(published: true)
end
end
def self.drafts
exclude published
end
def self.rank
published.desc(:comments_count)
end
def self.best_article_ever
rank.limit(1).first
end
def self.comments_average
query.average(:comments_count)
end
end
mapper = Lotus::Model::Mapper.new do
collection :authors do
entity Author
attribute :id, Integer
attribute :name, String
end
collection :articles do
entity Article
attribute :id, Integer
attribute :author_id, Integer
attribute :title, String
attribute :comments_count, Integer
attribute :published, Boolean
end
end
adapter = Lotus::Model::Adapters::SqlAdapter.new(mapper, connection_uri)
AuthorRepository.adapter = adapter
ArticleRepository.adapter = adapter
mapper.load!
author = Author.new(name: 'Luca')
AuthorRepository.create(author)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment