post.rb 2.8 KB
class Post < ActiveRecord::Base
  attr_accessible :title, :flag, :detail, :chan, :cate, :words, :parent_id, :isdel

  CATE = {
    'ranges' => {
      name: '诺正业务',
      cate: {
        # 'kyly'  => '科研领域',
        'spncp' => '食品/农产品检测',
        # 'ncpjc' => '农产品检测',
        # 'rzpjc' => '肉制品检测',
        'hjjc'  => '环境检测',
        # 'swjc'  => '生物检测',
        # 'yyjc'  => '医药检测',
        'xfjc'  => '消防检测',
        'rhpjc' => '日化品检测',
        'hfsl'  => '化肥/饲料检测',
        'sfjd'  => '环境损害司法鉴定',
        # 'jtjjc' => '添加剂检测',
      }
    },
    'sources' => {
      name: '资源中心',
      cate: {
        # 'zscx' => '证书查询',
        'bgcx' => '报告查询',
        'wssj' => '网上送检'
      }
    },
    'dynamics' => {
      name: '诺正动态',
      cate: {
        'gsdt' => '公司动态',
        'hykx' => '行业快讯',
        'pxxx' => '培训学习'
      }
    },
    'cultures' => {
      name: '诺正文化',
      cate: {
        'jzg'  => '诺正价值观',
        # 'hj'   => '诺正环境',
        # 'yj'   => '诺正愿景',
        # 'ygfc' => '员工风采',
        # 'zd'   => '诺正制度',
        'js'   => '诺正精神'
      }
    },
    'abouts' => {
      name: '关于诺正',
      cate: {
        'gsjj' => '公司简介',
        'jclc' => '检测流程',
        'yjss' => '硬件设施',
        'fwcn' => '服务承诺',
        # 'lxwm' => '联系我们'
      }
    },
    'contact' => {
      name: '联系我们',
      cate: {
        'lxdz' => '联系地址'
      }
    },
    'jobs' => {
      name: '招贤纳士',
      cate: {
        'shzp' => '社会招聘',
        'xyzp' => '校园招聘'
      }
    }
  }

  BaseArr = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']

  validates_presence_of :title, :detail, :chan, :cate, message: '不能为空'
  validates_uniqueness_of :flag, allow_blank: true, message: '已存在'
  
  def to_param
    flag
  end

  def flag=(val)
    if flag.blank?
      write_attribute(:flag, val.blank? ? shorturl : val)
    else
      if flag != val and val.present?
        write_attribute(:flag, val)
      end
    end
  end
  
  def shorturl
    hex       = Digest::MD5.hexdigest("base_key" + Time.now.to_f.to_s)
    output    = []
    4.times do |i|
      str    = hex[(i * 8)...(8 * (i + 1))]
      int    = 0x3FFFFFFF & ('0x' + str).to_i(16)
      out    = ''
      6.times do
        out  += BaseArr[0x0000003D & int]
        int  = int >> 5
      end
      output << out
    end
    output.sort_by{rand}[0]
  end
end