`

测试ruby代码高亮

 
阅读更多
# encoding: utf-8
require 'digest/sha2'

class User < ActiveRecord::Base
  validates :email, format: {with: /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, message: '请填写有效电子邮箱'}, :on => :create
  validates :password, format: {with: /^[a-zA-Z0-9~@#%&_\.\-\^\$\*\!\+\=]{6,16}$/,message: '必须由6-16个字母、数字或特殊字符组成'}, :on => :create
  validates :password, :confirmation => true , :on => :create
  validates :name ,format: {with: /^[\u4e00-\u9fa5]{2,4}$/,message: '中文姓名必须由2到4个汉字组成'}
  validates :city ,format: {with: /^[\u4e00-\u9fa5]{2,10}$/,message: '地名必须由2到10个汉字组成'}
  validates :agree, inclusion: { in: %w(1), message: "%{value} is invalid." }
  validates :status, inclusion: { in: %w(0 1 2), message: "%{value} is invalid." }
  validates :gender, inclusion: { in: %w(0 1), message: "%{value} is invalid." }
   
  attr_accessor :password_confirmation
  attr_reader   :password

  validate  :password_must_be_present
  validate  :email_unique, :on=> :create
  
  before_create	:make_activation_code, :set_pinyin
  
  has_many :posts
  has_many :comments
  has_many :groups

  
  has_many :requestee_relationships,:class_name=>"Relationship",:foreign_key=>"requester_id"
  has_many :requestees,:through=>:requestee_relationships,:source=>:requestee
  
  has_many :requester_relationships,:class_name=>"Relationship",:foreign_key=>"requestee_id"
  has_many :requesters,:through=>:requester_relationships,:source=>:requester
    
  STATUS = {"0" => "未工作","1"=>"在上学" ,"2"=>"在工作"}
  UserPath="#{Rails.root.to_s}/public/uploads/users"
  #UserPath="#{Rails.root.to_s}/public/上传/用户"
  
  
  # 'password' is a virtual attribute
  def password=(password)
    @password = password

    if password.present?
      generate_salt
      self.encrypted_password = self.class.encrypt_password(password, salt)
    end
  end
  
  def active?
    activation_code.nil?
  end
  
  # Activates the user in the database.
  def activate!
    activate
    save(:validate => false)
  end
  
  def activate
    @activated = true
    self.activated_at = Time.now
    self.activation_code = nil
  end
 
  # Returns true if the user has just been activated.
  def recently_activated?
    @activated
  end
=begin
select user_id,count(user_id) as same  from friendships where friend_id in (select friend_id from friendships  where user_id=1 ) and user_id in (6,7,8,9,10,16,17,18,19,20) and friend_id<>1 group by user_id order by same desc
=end
  #有共同好友的,从好友的好友中找,不包含已经发送请求或是好友关系的 
  def suggested_friends
    rs1=Relationship.where("requester_id='#{self.id}' and (status='pending' or status='accepted')")
    ids1= rs1.map{|r| r.requestee_id}
    rs2=Relationship.where("requestee_id='#{self.id}' and (status='pending' or status='accepted')")
    ids2 = rs2.map{|r| r.requester_id}
    rs3 = User.all(:conditions=>["activation_code is NULL and id not in (?)",ids1+ids2+[self.id]]) 
    ids3 =rs3.map{|r| r.id}
    _ids3=ids3.join(",")
    rs=ActiveRecord::Base.connection.execute("select user_id,friend_id  from friendships where friend_id in (select friend_id from friendships  where user_id='#{self.id}' ) and user_id in (#{_ids3}) and friend_id<>'#{self.id}'")
		hash={}
		rs.each_with_index do |r,i|
		   hash[r[0]]=[] if hash[r[0]].nil?
		   hash[r[0]] << r[1]
		end
		users = rs3.select{|r| hash.keys.include? r.id}
		users.sort_by! {|u| -hash[u.id].count}
		return 	users,hash
  end
  
  def search(keyword)
    rs1=Relationship.where("requester_id='#{self.id}' and (status='pending' or status='accepted')")
    ids1= rs1.map{|r| r.requestee_id}
    rs2=Relationship.where("requestee_id='#{self.id}' and (status='pending' or status='accepted')")
    ids2 = rs2.map{|r| r.requester_id}
    User.all(:conditions=>["activation_code is NULL and id not in (?)",ids1+ids2+[self.id]])
  end
  
  def is_friend_of?(user_id)
    arr1 = Relationship.where("requester_id='#{self.id}' and requestee_id='#{user_id}'")
    arr2 = Relationship.where("requestee_id='#{self.id}' and requester_id='#{user_id}'")
    return true if !arr1.empty? and arr1[0].status=="accepted" 
    return true if !arr2.empty? and arr2[0].status=="accepted" 
    return false 
  end
  
  def friends(group)
    if group.nil? or group=~/^\-\d+$/ or group=~/^\d+$/
		  _group = group.to_i
		  if group.nil? or _group ==-3
				 a = self.requesters.where("relationships.status='accepted'")
				 b = self.requestees.where("relationships.status='accepted'")
				 return a+b
		  elsif _group>-3
		    fs= Friendship.where("user_id='#{self.id}' and group_id='#{group}'")
		    ids = fs.map{|f| f.friend_id }
		    return User.all(:conditions=>["id  in (?)",ids]) 
		  end
		 elsif ('a'..'z').include?(group.downcase)
		   fs= Friendship.where("user_id='#{self.id}'")
		   ids = fs.map{|f| f.friend_id }
		   return User.all(:conditions=>["id in (?) and pinyin like ?",ids,"#{group.downcase}%"]) 
		 else
		   []
    end
  end
  
  def self.same_friend(user_id,id)
    rs=ActiveRecord::Base.connection.execute("select user_id,friend_id  from friendships where friend_id in (select friend_id from friendships  where user_id='#{user_id}' ) and user_id='#{id}' and friend_id<>'#{user_id}'")
    rs.count
  end

=begin
select distinct relationships.requestee_id,friendships.group_id from relationships left join friendships on friendships.relationship_id=relationships.id  where relationships.requester_id=1 and relationships.status='accepted';

select distinct relationships.requester_id,friendships.group_id from relationships left join friendships on friendships.relationship_id=relationships.id  where relationships.requestee_id=1 and relationships.status='accepted';
=end
 
  class << self
    def birth(year,month,day)
      #20.days.ago.to_date.to_s
      return year + "-" +month+ "-" +day
    end    
    
    def authenticate(email, password)
				if user = find_by_email(email)
				  if user.encrypted_password == encrypt_password(password, user.salt)
				    if user.active?
				      return [true,user]
				    else
				      return [false,user]
				    end
				  end
				end
				[false,nil]
    end

		 def encrypt_password(password, salt)
			  Digest::SHA2.hexdigest(password + "wibble" + salt)
		 end
		 
		 def secure_digest(*args)
      Digest::SHA2.hexdigest(args.flatten.join('--'))
    end
    
		 def make_token
			 secure_digest(Time.now, (1..10).map{ rand.to_s })
		 end
		 
		 def valid_image?(file)
		   format = file.original_filename.split(".")[-1] =~ /jpg|jpeg|png|gif|bmp/
		   size = file.size <= 2*1024*1024 #小于2M
		   format&&size
		 end
  end
  
  def User.another_user?(current_user,another)
    current_user && current_user.id != another.to_i
  end
  
  def self.upload_logo(hash)
    path= "/#{hash[:id]}/logo"
    FileUtils.mkdir_p "#{UserPath}#{path}"
    original_type = hash[:uploaded_logo].original_filename.split(".")[-1]
    basename = File.basename(hash[:uploaded_logo].original_filename,".*")
    
    _now = Time.now.strftime("%Y%m%d%H%M%S")
    _path = "/#{UserPath.split("/")[-2..-1].join("/")}"
    logo_name = basename.force_encoding("UTF-8")
    save_logo_path = "#{UserPath}#{path}/#{logo_name}_#{_now}.#{original_type}" 
    logo_path="#{_path}#{path}/#{logo_name}_#{_now}.#{original_type}"
     
    small_logo_name = "#{basename}_small"
    save_small_logo_path="#{UserPath}#{path}/#{small_logo_name}#{_now}.#{original_type}" 
    small_logo_path="#{_path}#{path}/#{small_logo_name}#{_now}.#{original_type}" 
     
    medium_logo_name = "#{basename}_medium"
    save_medium_logo_path="#{UserPath}#{path}/#{medium_logo_name}#{_now}.#{original_type}"
    medium_logo_path="#{_path}#{path}/#{medium_logo_name}#{_now}.#{original_type}"
    
    large_logo_name = "#{basename}_large"
    save_large_logo_path = "#{UserPath}#{path}/#{large_logo_name}#{_now}.#{original_type}"
    large_logo_path = "#{_path}#{path}/#{large_logo_name}#{_now}.#{original_type}"
    
    File.open(save_logo_path,"wb") do |file|
      file.write hash[:uploaded_logo].read
    end 
    img = Magick::Image.from_blob(hash[:uploaded_logo].read)[0]
    img.write(save_logo_path)
    
		 thumbnail = img.resize_to_fill(50, 50)
		 thumbnail.write(save_small_logo_path)
		 
		 thumbnail = img.resize_to_fill(120, 120)
		 thumbnail.write(save_medium_logo_path)
		 
		 thumbnail = img.resize_to_fill(180, 180)
		 thumbnail.write(save_large_logo_path)
		 [logo_name,logo_path,small_logo_path,medium_logo_path,large_logo_path]
  end
  
  private

  def password_must_be_present
    errors.add(:password, "Missing password") unless encrypted_password.present?
  end
  
  def email_unique
		 if User.find_by_email(self.email)
		   errors.add(:email,"该邮箱已经注册,请您换一个邮箱")
		 end
  end
  
  def birth_valid?(year, month,day)
    begin
      @date = Date.new(year.to_i, month.to_i, day.to_i)
      return @date>=Date.new(1900,1,1)&&@date<=Time.now.to_date
    rescue ArgumentError
      return false
    end
  end
  
  def check_birth
    unless birth_valid?
      errors.add(:birth,"日期格式错误或不在范围内")
    end
  end

  def generate_salt
    self.salt = self.object_id.to_s + rand.to_s
  end
  
  def make_activation_code
    self.activation_code = self.class.make_token
  end
  
  def set_pinyin
    self.pinyin = PinYin.of_string(self.name, :ascii).join.gsub!(/\d/,"")
  end
end


=begin
self.errors.add_to_base(self.class.instance_variable_get(:@message)) 
self.errors.add(:captcha, self.class.instance_variable_get(:@message))
flash.now[:error]            
@reply.errors.full_messages.join(',')

DUPLICATE_RECORD_ERRORS = [
  /^Mysql::Error:\s+Duplicate\s+entry\b/,
  /^PG::Error:\s+ERROR:\s+duplicate\s+key\b/,
  /\bConstraintException\b/
]

def self.duplicate_record_error?(error)
  error.class.name == 'ActiveRecord::RecordNotUnique' or
  DUPLICATE_RECORD_ERRORS.any? { |re| re =~ error.message }
end
=end
 

 

分享到:
评论

相关推荐

    Ruby-Rouge一个纯ruby代码高亮显示并与与pygments兼容

    Ruby Rouge 是一个强大的纯 Ruby 实现的代码高亮库,设计用于替代 Python 的 Pygments 库,同时保持兼容性。这个库特别适用于那些在 Ruby 环境中工作且需要进行代码格式化和高亮显示的开发者。Ruby Rouge 的优势在于...

    ruby-使用ruby开发的跨平台代码编辑器.zip

    3. **文本处理和语法高亮**:Ruby提供了强大的字符串操作功能,我们可以利用正则表达式处理文本,实现代码高亮显示。例如,我们可以为不同类型的编程语句或关键字定义颜色样式,并在用户输入时实时更新。 4. **代码...

    Ruby编辑器scite F5可以运行

    Scite不仅提供基本的文本编辑功能,还具备代码高亮、自动完成、宏录制与回放等特性,极大地提高了程序员的开发效率。 在Ruby开发中,Scite作为一个便捷的编辑器,其F5快捷键的运用是尤为关键的。F5通常被设置为执行...

    Ruby Eclipse插件

    1. **代码高亮**:Ruby Eclipse插件为Ruby源代码提供语法高亮,使得代码更易读,有助于程序员快速识别关键字、变量、函数等元素。 2. **自动完成**:在编写代码时,插件能提供智能感知功能,根据上下文提示可能的...

    Ruby-irbtools改善Ruby的IRB控制台

    Ruby IRB(Interactive Ruby)是Ruby语言的标准交互式shell,允许开发者在运行时测试代码、探索类库和调试程序。然而,IRB本身的功能相对基础,对于一些高级的开发需求可能显得不够用。这就是irbtools的出现,它为...

    ruby eclipse插件

    它提供了代码编辑器、调试器、项目管理、自动完成等特性,帮助开发者高效地编写和测试Ruby代码。 2. **artifacts.jar**:这个文件通常包含了插件的元数据和其他依赖项,用于Eclipse识别和加载插件。它确保了插件在...

    SciTE安装包,用于ruby

    这个安装包可能是专门为Ruby开发者优化过的版本,具有代码高亮、自动完成、语法检查等功能,以提升编写Ruby代码的效率。 描述中提到"2015年9月30更新的",这意味着该版本的SciTE编辑器是2015年的,可能不包含后来...

    Hello, Ruby World!

    - **交互式环境**:Ruby提供了IRB(Interactive Ruby Shell)这样的交互式环境,允许开发者在命令行中直接执行Ruby代码,便于调试和学习。 ##### 4. IRB与Pry - **IRB**:IRB是一个强大的交互式Ruby shell,可以...

    ruby RDT&RadRails(Eclipse下的插件)

    Ruby RDT使得在Eclipse中编写、运行和测试Ruby代码变得异常方便,同时它还能够集成其他版本控制系统,如Git或SVN,帮助开发者更好地管理代码版本。 RadRails则是Ruby on Rails的专用开发工具,它是在Ruby RDT的基础...

    Discuz5.5.0代码高亮显示+运行代码框合成插件 下载第1/4页

    总结来说,Discuz5.5.0代码高亮显示+运行代码框合成插件通过集成代码高亮和代码运行框的多项功能,极大地增强了社区论坛在代码交流方面的能力,满足了程序员和开发者的实际需要,推动了网络社区在技术交流方面的进步...

    RDT ruby development tool eclipse plugin

    1. **代码编辑器**:RDT提供了具有语法高亮、自动缩进、代码折叠、错误检查和快速修复的代码编辑器,帮助开发者更轻松地编写Ruby代码。 2. **代码导航**:通过实现代码跳转、查找引用、查看定义等操作,便于理解代码...

    ruby 安装程序

    为了编写和运行Ruby代码,还需要一个文本编辑器或IDE,如Visual Studio Code、Atom或RubyMine。这些工具通常有集成的Ruby支持,包括代码高亮、自动补全和调试功能。 总的来说,Ruby的安装过程包括下载安装包、配置...

    Ruby动态编程对象编程Ruby动态编程对象编程Ruby动态编程对象编程

    - Visual Studio Code、Sublime Text等编辑器支持Ruby插件,提供代码高亮、智能提示等功能。 **2. 学习资源** - **官方文档** - Ruby官网提供了详尽的文档,包括语言参考、API文档等。 - **书籍推荐** - 《Ruby...

    MCBBSWikiPrismLoader:为MCBBSWiki提供代码高亮,高亮使用Prism开源插件

    MCBBSWikiPrismLoader是一款专门针对MCBBSWiki(一个关于Minecraft的中文社区百科)的代码高亮工具,其核心是利用了Prism开源插件来实现代码的美化和高亮显示。Prism是一个轻量级、可扩展且专注于代码高亮的...

    Ruby_Programming

    IRB (Interactive Ruby Shell) 是一个用于测试Ruby代码的交互式环境。 1. **启动IRB**: 在终端输入`irb`命令即可启动。 2. **理解输出**: IRB会显示每条命令的返回结果,便于调试和学习。 ### 基本Ruby: Hello ...

    Ruby-AutoHtml一组过滤器集合用于将纯文本转换成HTML代码

    描述中提到的“过滤器集合”,意味着AutoHtml包含多个预定义的过滤器,如链接、图像、视频、代码高亮等。每个过滤器都负责识别特定的文本模式并进行相应的HTML转换。开发者可以根据需要选择使用哪些过滤器,也可以...

    ruby windows

    Vim支持Ruby插件,可以提供语法高亮、代码补全等功能,提高Ruby开发效率。 5. **设置环境变量**: - 安装Ruby和DevKit后,确保在系统的PATH环境变量中包含了Ruby和DevKit的bin目录,以便在命令行中直接运行ruby和...

    ruby语法基础教程.pdf

    - irb是Ruby的交互式解释器,可以在其中直接执行Ruby代码,非常适合调试和测试小段代码。 **2.4 Ruby-ri** - ri是Ruby的在线帮助系统,可以查询Ruby语言的各种文档和手册。 **2.5 RubyGems** - RubyGems是Ruby的包...

Global site tag (gtag.js) - Google Analytics