Sha256: 804e560330bf61c8a2335a537678ea1648c752010b42b76adafcf605ac75f847

Contents?: true

Size: 1.76 KB

Versions: 1

Compression:

Stored size: 1.76 KB

Contents

require 'sinatra/activerecord'
require 'digest/md5'
require 'sqlite3'
require_relative 'time_ago'

ENV_NAME = ENV['RACK_ENV'] || 'development'

module Cachai

  def self.load_db!
    load_schema unless schema_loaded?
  end

  def self.load_schema
    require_relative '../db/schema.rb'
  end

  def self.schema_loaded?
    Post.first
    true
  rescue ActiveRecord::StatementInvalid => e
    # SQLite3::SQLException => e
    # return !e.message['no such table']
    false
  end

  class Post < ActiveRecord::Base
    has_many :responses

    validates_presence_of :path
    validates_uniqueness_of :path

    def self.find_or_create_by_path(path)
      find_by_path(path) || create({:path => path})
    end
  end

  class Response < ActiveRecord::Base
    belongs_to :post
    validates_presence_of :author_name, :author_name, :author_email, :content

    scope :approved, lambda { where(:approved => 1) }
    scope :comment, lambda { where(:response_type => 'comment') }
    scope :pingback, lambda { where(:response_type => 'pingback') }
    scope :top_level, lambda { where(:parent_id => 0) }
    scope :nested, lambda { where("parent_id != 0") }


    def as_json(options = {})
      {
        :id           => id,
        :author_name  => author_name,
        # :author_email => author_email,
        :author_img   => author_img,
        :author_url   => author_url,
        :content      => content,
        :timestamp    => created_at.to_i,
        :parent_id    => parent_id,
        :type         => response_type,
        # :created_at   => created_at,
        :created_ago  => Timeago.since(created_at)
      }
    end

    def author_img(size = 50)
      id = Digest::MD5::hexdigest(author_email.strip.downcase)
      "https://www.gravatar.com/avatar/#{id}.jpg?s=#{size}"
    end
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
cachai-0.0.4 lib/models.rb