home_controller.rb 1.58 KB
class HomeController < ApplicationController
  def index
  end

  # /:chan/:cate/:flag
  def show
    if @cate.blank?
      @cate = params[:cate] || @cates.keys[0]# 如果没有类别, 默认第一个为当前类别
      @cate_name = @cates[@cate]# 当前类别的中文名称
    end

    @posts     = Post.where(isdel: false, chan: params[:chan], cate: @cate).page(params[:page]).per(5).order('id desc')
    unless params[:page].to_i > 1
      @post    = @posts.first if @posts.length == 1
      @post    = @posts.find_by_flag(params[:flag]) if params[:flag].present?
      # 网页关键词
      if @post and @post.words
        keywords = @post.words.split(",") + @keywords.split(",")
        keystr = keywords.uniq.join(",")
        if keystr.length > 100 # 如果长度大于200截取, 删掉最后一个
          keywords = keystr[0..100].split(",")
          keywords.pop
          keystr = keywords.join(',')
        end
        @keywords = keystr
        if params[:flag].present?
          @title = @post.title + " 诺正检测 | NORMZ TESTING"
        end
      end
    end

    if params[:type] == 'api'
      posts = @posts.map do |post|
        img = post.detail.scan(/<img[^>]+src\s*=\s*(['\"][^'\"]+['\"])[^>]*>/).flatten.first.gsub(/\"/, '') rescue '/images/default_200x150.jpg'
        detail = post.detail.gsub(/<\/?.*?>/,"")[0..120]
        {title: post.title, flag: post.flag, detail: post.detail, sub_detail: detail, img: img}
      end
      post = {title: @post.title, flag: @post.flag, detail: @post.detail} if @post
      render json: {code: 200, posts: posts, post: post}
    end
  end
end