# encoding: utf-8
require 'mcrypt'
module Spg
class Aes
attr_accessor :key, :iv
def self.encrypt data
new.encrypt data
end
def self.decrypt data
new.decrypt data
end
def initialize
self.key = Settings.spg.hash_key
self.iv = Settings.spg.hash_iv
end
def encrypt data
crypto.encrypt(data).unpack("H*").last
end
def decrypt data
crypto.padding = :zeros
decrypt = crypto.decrypt([data].pack("H*"))
decrypt.encode('UTF-8', invalid: :replace, replace: '').match(/{.*}/)[0]
end
private
def crypto
@crypto ||= Mcrypt.new(:rijndael_128, :cbc, key, iv, :pkcs)
end
end
end
class CreatePhotos < ActiveRecord::Migrationdefchangecreate_table:photosdo|t|t.string:namet.string:filet.string:sizet.string:content_typet.integer:positiont.timestampsnull:falseendendend
db migrate
rake db:create ; rake db:migrate
建立 photo controller
rails g controller photos
設定 CarrierWave Uploader
rails generate uploader Photo
開始來寫
設定routes
config/routes.rb
Rails.application.routes.draw do
root to: 'photos#index'
resources :photos do
collection do
post :update_position
end
end
# ...
end
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
....
around_action :set_current_user
def set_current_user
User.current = current_user
yield
ensure
User.current = nil
end
end
app/models/user.rb
class User < ActiveRecord::Base
...
def self.current
Thread.current[:user]
end
def self.current=(user)
Thread.current[:user] = user
end
end
設定完後在 model 都可以直接用 User.current 直接取得現在 current_user