aboutsummaryrefslogtreecommitdiffstats
path: root/app/controllers/application_controller.rb
blob: c0af3c8c2c6848f73c6a4ff334467fc66afb4f31 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# -*- coding: utf-8 -*-
class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :set_format
  after_filter :xhtml
  before_filter :get_include_user

  def render_timeline(a = nil, &blk)
    @items = a || blk.call

    @items = @items.where("tweets.id <= ?", max_id) if max_id
    @items = @items.where("tweets.id > ?", since_id) if since_id

    if @force_page || page
      @items = @items.page(page || 1).per(count)
    else
      @items = @items.limit(count)
    end

    render "shared/tweets"
  end

  # params
  def page; get_int(params[:page], nil){|i| i > 0} end
  def count; get_int(params[:count], 10){|i| (1..100) === i} end
  def max_id; get_int(params[:max_id], nil){|i| i >= 0} end
  def since_id; get_int(params[:since_id], nil){|i| i >= 0} end
  def user_limit; get_int(params[:limit], 20){|i| i >= 0} end

  def force_page
    @force_page = true
  end

  def order
    case params[:order]
    when /^fav/
      :favorite
    when /^re?t/
      :retweet
    else
      :default
    end
  end

  private
  def set_format
    unless [:json, :html].include?(request.format.to_sym)
      request.format = :html
    end
  end

  def xhtml
    if request.format == :html
      response.content_type = "application/xhtml+xml"

      # remove invalid charactors
      response.body = response.body.gsub(/[\x0-\x8\xb\xc\xe-\x1f]/, "")
    end
  end

  def get_include_user
    @include_user ||= get_bool(params[:include_user])
  end

  def get_bool(str)
    /^(t|true|1)$/ =~ str
  end

  def get_int(str, default = 0, &blk)
    if str =~ /^[1-9]\d*$/
      i = str.to_i
      if !block_given? || blk.call(i)
        return i
      end
    end
    default
  end
end