Skip to content

Instantly share code, notes, and snippets.

@jhjguxin
Created November 28, 2012 12:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhjguxin/4160890 to your computer and use it in GitHub Desktop.
Save jhjguxin/4160890 to your computer and use it in GitHub Desktop.
paperclip Cropper 一次性 传入Cropper相关参数 和文件来裁剪 Base on BBTang compatible with IE
<div class="ps_ct_con avatar_edit" id = "profile_edit_avatar_<%= @profile.id%>" style=<%= (params[:action].eql? "edit_avatar") ? "display:block;" : "display:none;"%> >
<div class="l_new" style="display:block">
<%= form_for @profile, :url => post_avatar_profiles_path, :method => :post, :html => { :multipart => true,:class => "l_upload_profile_face" } do |f| %>
<div class="l_upload_photo">
<div class="l_add_wrap">
<div class="btns">
<%= f.file_field :face, class: "input_file" %>
<label for="input_file"><input id='file_mod_btn' name="" type="button" value='添加本地照片' /></label>
<% [:crop_x, :crop_y, :crop_w, :crop_h].each do |attribute| %>
<%= f.hidden_field attribute, :id => attribute %>
<% end %>
</div>
<p class="l_tip">你可以上传JPG、GIF、PNG、BMP图片文件,且文件小于2M</p>
</div>
<div class="l_photo_wrap">
<!--div class="l_photo_edit"-->
<%# image_tag 'l_upload_img.jpg', id: "old_avatar_pic"%>
<!--/div-->
<div class="l_photo_edit" >
<div class="old_avatar_middle" >
<div class="old_avatar_inner" >
<!--这里是要垂直居中的内容-->
<%= image_tag 'l_upload_img.jpg', id: "old_avatar_pic"%>
</div>
</div>
</div>
<div class="avatar_pic">
<div class="prew_avatar_pic">
<%= image_tag get_face_url(@profile, :size => :normal), id: "prew_avatar_pic"%>
</div>
<p>头像尺寸: 180 X 180像素</p>
<div class="l_save_usph">
<%= hidden_field_tag 'ie_submit', false%>
<%= f.submit "保存", :class=>"l_save_btn btn edit_avatar_submit", disable: true%>
<!--input type="button" value="取消" name="commit" class="save_btn btn"-->
</div>
</div>
</div>
</div>
<% end %>
<div class="l_normol">
如果无法上传头像,请尝试使用<a href="#nogo">普通上传模式</a>
</div>
</div>
<div class="old" style='display:none'>
<h3>让交流更真实</h3>
<%= form_for @profile, :url => post_avatar_profiles_path, :method => :post, :html => { :multipart => true, class: "upload_face_old" } do |f| %>
<div class="upload_photos">
<div class="up_pt_info">
<div class="avatar_pic">
<%= image_tag get_face_url(@profile, :size => :normal)%>
</div>
<div class="upload_info">
<!--
<p>从电脑中选择你喜欢的照片</p>
-->
<p>你可以上传JPG、GIF、PNG、BMP图片文件,且文件小于2M</p>
<div class="item">
<label for="profile_上传头像:">上传头像:</label>
<%= f.file_field :face, class: "input_file" %>
<%= f.submit "保存", :class=>"l_save_btn btn edit_avatar_submit", disable: true%>
</div>
<!--
<button class="up_btn" type="submit" name="">上传照片</button>
-->
</div>
</div>
<!--
<div class="up_pt_btn">
<button class="save_btn" type="submit" name="">保存</button>
<button class="cancel_btn" type="submit" name="">取消</button>
</div>
-->
</div>
<% end %>
<div class="return_new" style = "display:block">
返回<a href="#nogo">更多上传模式</a>
</div>
</div>
</div>
<% #crop if has params crop: true%>
<% if params[:crop].eql? "true"%>
<%= javascript_tag do%>
<% if @profile.errors.empty? and @profile.face.present? %>
$(document).ready(function() {
$("#old_avatar_pic").attr("src","<%= @profile.face.url(:original) %>")
$("#prew_avatar_pic").attr("src","<%= @profile.face.url(:original) %>")
set_old_img_style(img_id = 'old_avatar_pic')
imgareaselect(id='old_avatar_pic')
});
<% end %>
<% end %>
<% end %>
# encoding: utf-8
=begin
attachment 在相对应的model更新动作之前,所以 Cropper相关参数通过attachment.instance 来传递是行不通的。总是滞后的
所以 Cropper相关参数 和 attachment.instance 应该可以相关的
但总的有个地方来传进 Cropper相关参数
class ProfilesController < ApplicationController
def post_avatar
ip = request.env["REMOTE_ADDR"] if not request.env["REMOTE_ADDR"]=='127.0.0.1'
#get_ptag #get @tag_list
#@profile = Profile.find_by_user_id(current_user.id)
[:crop_x, :crop_y, :crop_w, :crop_h].each do |crop|
@profile.face.instance_write(crop, params[:profile][crop].to_f) if params[:profile][crop].present?
# reprocess! for ie
@profile.face.reprocess! unless params[:profile].has_key? :face
end
if @profile.update_attributes(params[:profile])
if params.has_key? :ie_submit and params[:ie_submit].eql? "true"
flash[:notice] = '头像更新成功,你可以按照你的需要裁剪!'
redirect_to edit_avatar_profiles_path(crop: true)
else
flash[:notice] = '头像更新成功!'
redirect_to edit_avatar_profiles_path
end
else
flash[:notice] = '头像更新失败!'
redirect_to edit_avatar_profiles_path
end
end
end
=end
module Paperclip
class Cropper < Thumbnail
=begin
def transformation_command
if crop_command
original_command = super
if original_command.include?('-crop')
original_command.delete_at(super.index('-crop') + 1)
original_command.delete_at(super.index('-crop'))
end
crop_command + original_command
else
super
end
end
def crop_command
target = @attachment.instance
if target.cropping?
["-crop", "#{target.crop_w}x#{target.crop_h}+#{target.crop_x}+#{target.crop_y}"]
end
end
=end
def transformation_command
if crop_command
crop_command + super.join(' ').sub(/ -crop \S+/, '').split(' ') # super returns an array like this: ["-resize", "100x", "-crop", "100x100+0+0", "+repage"]
else
super
end
end
def crop_command
target = @attachment
if cropping?
["-crop", "#{target.instance_read(:crop_w)}x#{target.instance_read(:crop_h)}+#{target.instance_read(:crop_x)}+#{target.instance_read(:crop_y)}"]
end
end
def cropping?
target = @attachment
!target.instance_read(:crop_x).blank? && !target.instance_read(:crop_y).blank? && !target.instance_read(:crop_w).blank? && !target.instance_read(:crop_h).blank?
end
protected
# Return true if the format is animated
def animated?
@animated && (ANIMATED_FORMATS.include?(@format.to_s) || @format.blank?) && identified_as_animated?
end
# Return true if ImageMagick's +identify+ returns an animated format
def identified_as_animated?
ANIMATED_FORMATS.include? identify("-format %m :file", :file => "#{@file.path}[0]").to_s.downcase.strip
rescue Cocaine::ExitStatusError => e
raise Paperclip::Error, "There was an error running `identify` for #{@basename}" if @whiny
rescue Cocaine::CommandNotFoundError => e
raise Paperclip::Errors::CommandNotFoundError.new("Could not run the `identify` command. Please install ImageMagick.")
end
end
end
gem "paperclip", "~> 3.0"
#http://stackoverflow.com/questions/12793158/paperclip-error-notidentifiedbyimagemagickerror
gem "cocaine", "= 0.3.2"
//http://woork.blogspot.com/2009/02/best-image-croppers-ready-to-use-for.html
$.extend($.imgAreaSelect, {
animate: function (fx) {
var start = fx.elem.start, end = fx.elem.end, now = fx.now,
curX1 = Math.round(start.x1 + (end.x1 - start.x1) * now),
curY1 = Math.round(start.y1 + (end.y1 - start.y1) * now),
curX2 = Math.round(start.x2 + (end.x2 - start.x2) * now),
curY2 = Math.round(start.y2 + (end.y2 - start.y2) * now);
fx.elem.ias.setSelection(curX1, curY1, curX2, curY2);
fx.elem.ias.update();
},
prototype: $.extend($.imgAreaSelect.prototype, {
animateSelection: function (x1, y1, x2, y2, duration) {
var fx = $.extend($('<div/>')[0], {
ias: this,
start: this.getSelection(),
end: { x1: x1, y1: y1, x2: x2, y2: y2 }
});
if (!$.imgAreaSelect.fxStepDefault) {
$.imgAreaSelect.fxStepDefault = $.fx.step._default;
$.fx.step._default = function (fx) {
return fx.elem.ias ? $.imgAreaSelect.animate(fx) :
$.imgAreaSelect.fxStepDefault(fx);
};
}
$(fx).animate({ cur: 1 }, duration, 'swing');
}
})
});
function preview(img, selection) {
var scaleX = 180 / (selection.width || 1);
var scaleY = 180 / (selection.height || 1);
$('img#prew_avatar_pic').css({
//width: Math.round(scaleX * 300) + 'px',
//height: Math.round(scaleY * 300) + 'px',
width: Math.round(scaleX * img.width) + 'px',
height: Math.round(scaleY * img.height) + 'px',
marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
});
//取得真实图片/裁剪框 的比值 确保 上传至服务器是准确的裁剪值
if ($.browser.msie || $("#prew_avatar_pic")[0].naturalWidth == null) {
var img = new Image();
img.src = $("#prew_avatar_pic")[0].src
var ratio_w = img.width / $("#old_avatar_pic").width()
var ratio_h = img.height / $("#old_avatar_pic").height()
} else {
var ratio_w = $("#prew_avatar_pic")[0].naturalWidth / $("#old_avatar_pic").width()
var ratio_h = $("#prew_avatar_pic")[0].naturalHeight / $("#old_avatar_pic").height()
};
if (! isNaN(selection.x1) ) {
$("#crop_x").val(selection.x1 * ratio_w);
$("#crop_y").val(selection.y1 * ratio_h);
$("#crop_w").val(selection.width * ratio_w);
$("#crop_h").val(selection.height * ratio_h);
}
}
//http://odyniec.net/projects/imgareaselect/usage.html
//persistent If set to true, clicking outside the selection area will not start a new selection (ie. the user will only be able to move/resize the existing selection area) default: false
function imgareaselect (id) {
var width = $("img#"+id).width();
var height = $("img#"+id).height();
$("img#"+id).imgAreaSelect({ x1: (width/2-25), y1: (width/2-25), x2: (height/2+25), y2: (height/2+25), aspectRatio: '1:1', handles: true, persistent: true, hide: false, minWidth: 50, minHeight:50, maxHeight:300, maxWidth: 300 ,onInit: preview, onSelectChange: preview, onSelectStart: preview });
}
//img file upload validate
$.validator.addMethod('filesize', function(value, element, param) {
if ($.browser.msie){
return true
} else {
return this.optional(element) || (element.files[0].size <= param)
}
});
//local img file prew
// File target is a <input type="file" />
function readURL(input_id,prew_img_id) {
input = $("#"+input_id)[0]
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#'+prew_img_id)
.attr('src', e.target.result)
//.width(150)
//.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
function set_old_img_style(img_id){
var cssObj = {
"max-width": "300px",
"max-height": "300px",
"_width": "300px",
"_height": "300px",
"text-align": "center",
"vertical-align": "middle",
//"position":"static !important",
//"position": "relative",
//"padding": "50% 50% 50% 50%",
//"top": "-50%",
//"left": "-50%",
"vertical-align": "middle"
}
$('#'+img_id).css(cssObj)
}
// validate for ie,which cannot work with file api
function profile_face_validator(profile_face){
if (profile_face == null) {
var profile_face = $("#profile_face")
}
var error_messages = {
required: "请选择一个图片",
accept: "图片文件必须是JPG,GIF,BMP或者PNG格式"}
//var profile_face = $("#profile_face")
var successed = false
// other simple validator for ie
if (profile_face.val() == null && profile_face.val() == ""){
humanMsg.displayMsg(error_messages.required);
} else {
if (profile_face.val().match(/png$|jpg$|gif$|bmp$|PNG&|JPG$|GIF&|BMP/) == null){
humanMsg.displayMsg(error_messages.accept);
} else {
successed = true
}
}
return successed
}
$(document).ready(function() {
if (! $.browser.msie){
// 非IE 主流 浏览器 验证
$('form.l_upload_profile_face').validate({
onfocusout: true,
onkeyup: true,
errorPlacement: function(error, element) {
//error.appendTo(element.parent().next());
//var error_text = error[0].innerText
var error_text = error[0].textContent
if (error_text != null && error_text != ""){
humanMsg.displayMsg(error_text);
}
// if ( element.is(":radio") )
// error.appendTo( element.siblings("span") );
// else if ( element.is(":checkbox") ){
// error.appendTo ( element.siblings("span") );
// }
// else
// error.appendTo( element.parent() );
},
invalidHandler: function() {
$("form.l_upload_profile_face input.save_btn").attr("disable","true")
},
success: function() {
//var id = 'profile_face'
//imgareaselect(id)
//readURL(input_id=id ,prew_img_id='old_avatar_pic')
//readURL(input_id=id ,prew_img_id='prew_avatar_pic')
//$("form.upload_photos input.save_btn").attr("disable","")
$("form.l_upload_profile_face input.save_btn").attr("disable","")
},
//success: function() {
submitHandler:function(form) {
var id = 'profile_face'
//imgareaselect(id)
//readURL(input_id=id ,prew_img_id='old_avatar_pic')
//readURL(input_id=id ,prew_img_id='prew_avatar_pic')
//imgareaselect(id='old_avatar_pic')
//$("form.upload_photos input.save_btn").attr("disable","")
$("form.l_upload_profile_face input.save_btn").attr("disable","")
form.submit();
}
});
//$('form.l_upload_profile_face').find("#profile_face") 与上层 form 绑定
if ($('form.l_upload_profile_face').find("#profile_face").length > 0){
$('form.l_upload_profile_face').find("#profile_face").rules("add", {
required: true,
accept: "image/*",
filesize: 2097152,
messages: {
required: "请选择一个图片",
accept: "图片文件必须是JPG,GIF,BMP或者PNG格式",
filesize: "图片文件必须小于2MB"
}
});
}
}
//jquery.validate似乎只在type=”submit”才会触发,当使用button类型的时候不起作用,看了一下手册发现了一个valid()方法可以手工触发验证,返回一个boolean值。
var profile_face = $('form.l_upload_profile_face').find("#profile_face")
profile_face.live('change',function() {
if ($.browser.msie){
if (profile_face_validator()) {
//手动提交表单
//$('form.l_upload_profile_face').serialize()
//$('form.l_upload_profile_face').serializeArray()
$("#ie_submit").val("true")
$('form.l_upload_profile_face').submit();
}
} else {
if (profile_face.valid()){
var id = 'profile_face'
//imgareaselect(id)
readURL(input_id=id ,prew_img_id='old_avatar_pic')
readURL(input_id=id ,prew_img_id='prew_avatar_pic')
set_old_img_style(img_id = 'old_avatar_pic')
imgareaselect(id='old_avatar_pic')
//$("form.upload_photos input.save_btn").attr("disable","")
$("form.l_upload_profile_face input.save_btn").attr("disable","true")
}
}
})
// IE内核浏览器 验证
var old_avatar_submit = $('form.upload_face_old').find('input.edit_avatar_submit')
old_avatar_submit.live('click',function() {
if (profile_face_validator(profile_face = $("form.upload_face_old #profile_face"))){
return true
} else {
return false
}
})
//$('form.l_upload_profile_face').find("#profile_face") 与上层 form 绑定
});
// 新旧两种 上传模式切换
$(document).ready(function() {
//切换至 旧模式
$(".avatar_edit .l_normol a").live('click',function() {
$(".avatar_edit .l_new").hide();
$(".avatar_edit .old").show();
$("img#old_avatar_pic").imgAreaSelect({hide: true})
return false;
});
//切换回 新模式
$(".avatar_edit .return_new a").live('click',function() {
$(".avatar_edit .l_new").show();
$(".avatar_edit .old").hide();
//
$("img#old_avatar_pic").imgAreaSelect({hide: true, disable: true})
//$("img#old_avatar_pic").imgAreaSelect({enable: true})
//<img alt="L_upload_img" id="old_avatar_pic" src="/assets/l_upload_img-665dd092d98def5bb330e478bb7f5b28.jpg">
//if ($("img#old_avatar_pic").attr('src').match(/l_upload_img\.jpg/) == null && $("img#old_avatar_pic").attr('src') != ''){
if ($("img#old_avatar_pic").attr('src').match(/l_upload_img/) == null && $("img#old_avatar_pic").attr('src') != ''){
imgareaselect("old_avatar_pic")
$("img#old_avatar_pic").imgAreaSelect({hide: false, enable: true})
//$("img#old_avatar_pic").attr('src')
}else{
$("img#old_avatar_pic").attr('src',"/assets/l_upload_img.jpg")
}
return false;
});
// tab 切换后 隐藏 imgAreaSelect
$(".avatar_edit").bind('style_display_change', function() {
console.log($(this).css('display'));
$("img#old_avatar_pic").imgAreaSelect({hide: true, disable: true})
if ($(this).css('display') == "none"){
//$("img#old_avatar_pic").imgAreaSelect({hide: true, disable: true})
} else {
if ($(".avatar_edit div.l_new").css('display') != "none"){
//$("img#old_avatar_pic").imgAreaSelect({enable: true})
//<img alt="L_upload_img" id="old_avatar_pic" src="/assets/l_upload_img-665dd092d98def5bb330e478bb7f5b28.jpg">
//if ($("img#old_avatar_pic").attr('src').match(/l_upload_img\.jpg/) == null && $("img#old_avatar_pic").attr('src') != ''){
if ($("img#old_avatar_pic").attr('src').match(/l_upload_img/) == null && $("img#old_avatar_pic").attr('src') != ''){
imgareaselect("old_avatar_pic")
$("img#old_avatar_pic").imgAreaSelect({hide: false, enable: true})
//$("img#old_avatar_pic").attr('src')
}else{
//$("img#old_avatar_pic").imgAreaSelect({hide: true})
$("img#old_avatar_pic").attr('src',"/assets/l_upload_img.jpg")
}
}
}
});
})
//城市弹出层
$("#btn_location").live("click",function() {
$("#pop_city").show();
$(".province_citys").addClass("hidden");
$(".sl_ad_close").live("click",function() {
$("#pop_city").hide();
});
});
var pryName, cityName;
$("#provinces_list a").live("click",function() {
var pryParent = $(this).parents(".panel_link");
var pryTag = $(this).attr("href");
if ($(this).parent().hasClass("municipality")) {
$("#pop_city").hide();
}
$(".province_citys").each(function(i) {
var cityTitle = $(".province_citys").eq(i).attr("title");
if (pryTag.indexOf(cityTitle) > -1) {
$(".province_citys").addClass("hidden");
$(".province_citys").eq(i).removeClass("hidden");
};
});
$("a", pryParent).removeClass("prov_cur");
$(this).addClass("prov_cur");
pryName = $(this).text();
$(".city_txt").html(pryName);
$("#profile_city").val(pryName);
return pryName;
});
$("#province_show a").live("click",function() {
//cityName = pryName + $(this).text();
cityName = $(this).text();
$(".city_txt").html(cityName);
$("#profile_city").val(cityName);
$("#pop_city").hide();
$("i.city_txt").change();
});
$("#direct_city a").live("click",function(){
var dirCity = $(this).text();
$(".city_txt").html(dirCity);
$("#profile_city").val(dirCity);
$("#pop_city").hide();
$("i.city_txt").change();
});
//滑动条
var sliderMod = {
init: function(cateStage) {
if (cateStage == "" || cateStage == 0 ) {
cateStage1 = 13;
} else {
cateStage1 = 13 + (cateStage) * 88;
}
$("#status_link1 .ui-slider-handle").css("left", cateStage1 + "px");
$("#slider-status").slider({
change:function(){
var curPos = parseInt($("#status_link1 .ui-slider-handle").css("left"));
if (curPos >= 0 && curPos < 60) {
$("#status_link1 .ui-slider-handle").css("left","13px");
$("#cate_wrap a").eq(0).click();
}
if (60 < curPos && curPos < 150) {
$("#status_link1 .ui-slider-handle").css("left","101px");
$("#cate_wrap a").eq(1).click();
}
if (150 < curPos && curPos < 230) {
$("#status_link1 .ui-slider-handle").css("left","189px");
$("#cate_wrap a").eq(2).click();
}
if (230 < curPos && curPos < 340) {
$("#status_link1 .ui-slider-handle").css("left","277px");
$("#cate_wrap a").eq(3).click();
}
}
});
$("#cate_wrap a").each(function(i) {
$(this).live("click",function() {
$("#profile_pregnancy_status").val(i+1);
var catePosX = 13 + i * 88;
$("#status_link1 .ui-slider-handle").css("left", catePosX + "px");
switch (i*1)
{
case 0:
$(".baby_predict").hide();
$(".baby_plan").show();
$(".baby_ready").hide();
break;
case 1:
$(".baby_predict").show();
$(".baby_plan").hide();
$(".baby_ready").hide();
break;
case 2:
$(".baby_predict").hide();
$(".baby_plan").hide();
$(".baby_ready").show();
break;
default:
$(".baby_predict").hide();
$(".baby_plan").hide();
$(".baby_ready").hide();
};
return cateStage = i;
});
});
}
};
jQuery(document).ready(function($){
var pregnancy_status = $("#profile_pregnancy_status").val()*1-1+''
sliderMod.init(cateStage =pregnancy_status, $("#profile_pregnancy_status").val());
sliderMod.init(cateStage =pregnancy_status, $("#profile_pregnancy_status").val());
var ppsVal = pregnancy_status;
switch (ppsVal) {
case "0":
$(".baby_predict").hide();
$(".baby_plan").show();
$(".baby_ready").hide();
break;
case "1":
$(".baby_predict").show();
$(".baby_plan").hide();
$(".baby_ready").hide();
break;
case "2":
$(".baby_predict").hide();
$(".baby_plan").hide();
$(".baby_ready").show();
break;
};
$('#_child_pre_birthday').change(
function(){
$("#profile_child_birthday").val($("#_child_pre_birthday").val());
});
$('#profile_child_birthday').change(
function(){
$("#_child_pre_birthday").val($("#profile_child_birthday").val());
});
var guess_city = $('b.cc_city em label').text()
if (guess_city != "")
{
$("#profile_city").val(guess_city)
};
$("i.city_txt").change(function(){
$("b.cc_city").delay(2000).fadeOut(400);
d})
});
jQuery(document).ready(function($){
//添加宝宝信息
var babyAdd = 0;
$(".baby_add").live("click",function(){
if ($(".baby_add_1").css("display") =="block"){
babyAdd = 1;
}
if ($(".baby_add_2").css("display") =="block"){
$(".baby_add_2").show();
$(this).hide();
}
if (babyAdd == 0) {
$(".baby_add_1").show();
babyAdd = 1;
}else {
$(".baby_add_2").show();
$(this).hide();
}
});
//展开收缩+-
$(".tag_recommend .shrink_icon").live("click",function(){
$(".personal_tag").toggle();
$(this).toggleClass("turn_state")
})
$(".contact_mode .shrink_icon").live("click",function(){
$(".pe_co_form").toggle();
$(this).toggleClass("turn_state")
})
//预产期计算工具
$("#ycq_count").live("click",function(){
$(".ycq_count_tool").show();
})
$(".yct_hd .close").live("click",function(){
$(".ycq_count_tool").hide();
})
$('#cal_yuchanqi').live("click",function(){
yuchanqi()
//$(".ycq_count_tool").delay(2000).fadeOut(400);
});
//排卵期计算工具
$("#plq_count").live("click",function(){
$(".plq_count_tool").show();
})
$(".plq_hd .close").live("click",function(){
$(".plq_count_tool").hide();
})
});
function update_ptag(tag_list){
$.ajax({
type: "post",
url: "/profiles/update_ptag",
data : {
tag_list : tag_list,
},
success: function(result) {
console.log("SUCCESS");
console.log(result);
},
error: function(result) {
console.log("ERROR");
console.log(result);
}
});
}
//ajax update_ptag
jQuery(document).ready(function($){
$("#update_ptag_button").live("click",function(){
if ($("#profile_tag_list").val() != "")
{
update_ptag(tag_list=$("#profile_tag_list").val())
}
})
});
// sync pregnancy display
jQuery(document).ready(function($){
var pregnancy_timeline = ["孕早期","孕中期","孕晚期"]
if ($("#profile_pregnancy_timeline").val() != "")
{
var index = $("#profile_pregnancy_timeline").val()*1-1
$("strong.pregnancy").text(pregnancy_timeline[index])
}
$("#profile_pregnancy_timeline").change(function(){
if ($("#profile_pregnancy_timeline").val() != "")
{
var index = $("#profile_pregnancy_timeline").val()*1-1
$("strong.pregnancy").text(pregnancy_timeline[index])
}
})
});
//ajax black_list autocomplate
jQuery(document).ready(function($){
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
var relate_user_cache = {},
lastXhr;
if ($("#new_blacklist").length > 0){
$("#new_blacklist")
// don't navigate away from the field on tab when selecting an item
/*.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
})*/
.autocomplete({
delay: 0,
minLength: 0,
focus: function( event, ui ) {
$( "#project" ).val( ui.item.label );
return false;
},
source: function( request, response ) {
var term = request.term;
if ( term in relate_user_cache ) {
response( relate_user_cache[ term ] );
return;
}
lastXhr = $.getJSON( '/profiles/relate_user', request, function( data, status, xhr ) {
relate_user_cache[ term ] = data;
if ( xhr === lastXhr ) {
response( data );
}
});
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 0 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
var tmp = $("#add_user_list").val()
$("#add_user_list").val(ui.item.id+","+tmp)
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li id= user_"+item.id+"></li>" )
.data( "item.autocomplete", item )
.append( "<a>"+"<img src=" + item.icon+ " width='32' height='32'/>" + item.label + "<br>" + "</a>" )
.appendTo( ul );
};
console.log("#new_blacklist chage");
}
});
function follow_user(link, followable_type) {
var followable_id = $(link).attr("user_id")
$.ajax({
url : "/profiles/add_collection",
type : "post",
async: false,
data : {
followable_id : followable_id,
followable_type : followable_type
},
beforeSend : function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
},
success : function(transport) {
//if(transport == '需要登录') {
// window.location.href = '/users/sign_in';
//} else {
$(link).attr("class","add_attent has_add_attent")
$(link).text("已关注")
//}
},
error : function(jqXHR, textStatus) {
if(jqXHR.status == "401") {
window.location.replace('/users/sign_in')
}
}
})
};
function unfollow_user(link,followable_type) {
followable_id = $(link).attr("user_id")
$.ajax({
url : "/profiles/delete_collection",
type : "post",
async: false,
data : {
followable_id : followable_id,
followable_type : followable_type
},
beforeSend : function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
},
success : function(transport) {
if(transport == '需要登录') {
window.location.href = '/users/sign_in';
} else {
$(link).attr("class","add_attent")
$(link).text("+关注")
//g("collection").innerHTML = '已收藏[' + transport + ']';
}
},
error : function() {
//请求出错处理
}
})
};
function follow_or_unfollow(link){
if ($(link).attr("class") == "add_attent"){
follow_user(link = link,followable_type = "User")
}else if ($(link).attr("class") == "add_attent has_add_attent"){
unfollow_user(link = link,followable_type = "User")
}else{
//not match nothing to do ...
}
}
// profile recomment follow and stop follow
jQuery(document).ready(function($){
//call for each recomment obj
$(".add_attent").each(function(){
$(this).live("click",function() {
follow_or_unfollow(this)
})
});
$("#followallexperts").live("click",function(){
$(".add_attent").not(".has_add_attent").each(function() {
follow_user(link = this,followable_type = "User")
});
})
$("#followallusers").live("click",function(){
$(".add_attent").not(".has_add_attent").each(function() {
follow_user(link = this,followable_type = "User")
});
})
/*
$(".add_attent").not(".has_add_attent").each(function() {
follow_user(link = this,followable_type = "User")
});
$(".has_add_attent").each(function() {
unfollow_user(link = this,followable_type = "User")
});
*/
});
//添加标签列表
$("#ptb_tag_list i").bind({
mouseover:function(){$(this).addClass("put");},
mouseout:function(){$(this).removeClass("put");},
click:function(){$(this).parent().hide();}
});
//黑名单列表
$("#bll_list i").bind({
mouseover:function(){$(this).addClass("put");},
mouseout:function(){$(this).removeClass("put");},
click:function(){$(this).parent().hide();}
});
# encoding: utf-8
class Profile < ActiveRecord::Base
#alias_attribute :pregnancy_status, :pregnancy_timeline
attr_accessor :crop_x, :crop_y, :crop_w, :crop_h
#attr_accessible :oauth_face_image_url # for getter and setters
profile_face_url = "/uploads/paperclip/:class/:attachment/:id/:style/:filename"
profile_face_path =":rails_root/public/uploads/paperclip/:class/:attachment/:id/:style/:filename"
#profile_face_url = Askjane::MetaCache.get_config_data("profile_face_url")
#profile_face_path = Askjane::MetaCache.get_config_data("profile_face_path")
attr_accessible :face, ,:crop_x, :crop_y, :crop_w, :crop_h
=begin
has_attached_file :face,:default_url => "/assets/face/:style/missing.png",
:default_style => :s120,
:styles => {
:normal => "180x180#",
:s120 => "120x120#",
:s48 => "48x48#",
:s32 => "32x32#",
:s16 => "16x16#"
},
:url => profile_face_url,
:path => profile_face_path
=end
has_attached_file :face,:default_url => "/assets/face/:style/missing.png",
:default_style => :s120,
:styles =>
lambda { |a|
{
:normal => "180x180#",
:s120 => "120x120#",
:s48 => "48x48#",
:s32 => "32x32#",
:s16 => "16x16#"
}
},
:url => profile_face_url,
:path => profile_face_path,:processors => [:cropper]
#,:convert_options => { :normal => "-gravity Center -crop 50x50+0+0 +repage" }
#validates_attachment :face, :presence => true,
validates_attachment :face,
:content_type => {:content_type => ['image/jpg', 'image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png', 'image/bmp']}, :allow_nil=>true
#:size => { :in => 0..2.megabytes }
#validates :face, :attachment_presence => true
#validates_with AttachmentPresenceValidator, :attributes => :face
validates_attachment_size :face, :less_than => 2.megabytes,
:unless => Proc.new {|m| m[:face].nil?}
before_post_process :image?
def image?
#breakpoint
!((self.face.content_type =~ /^image\/*/).nil?)
end
def get_face_url(options = {})
#breakpoint
if self.present? && self.reload
local_face = options[:local_face] || false
size = options[:size] || "s120"
if not(local_face) and self.oauth_face_image_url and not (self.face?)
return self.oauth_face_image_url
else
return self.face.url(size)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment