Paperclip基本配置,图片的content_type是比较全了

1
2
3
4
5
6
7
8
9
10
has_attached_file :avatar,
    :styles => { :medium => "200x200>", :thumb => "100x100>" }

validates_attachment_content_type :avatar,
    :content_type => ['image/jpg', 'image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png'],
    :message => "only image files are allowed"

validates_attachment_size :avatar,
    :less_than => 1.megabyte, #another option is :greater_than
    :message => "max size is 1M"

>>发表评论

    Posted by holin At January 08, 2009 13:02

Alias for find

1
2
3
4
5
6
7
class <<ActiveRecord::Base
  alias_method :[], :find
end

Person[5]
Person[:last]
Person[:all, :conditions => { :name => "Jamis" }]

>>发表评论

    Posted by devon At January 08, 2009 12:33

Convert Filesize Bytes to Readable String in Javascript

1
2
3
4
5
6
7
function readablizeBytes(bytes) {
    var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB'];
    var e = Math.floor(Math.log(bytes)/Math.log(1024));
    return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e];
}

readablizeBytes(5000); // 4.88 kb

>>发表评论

    Posted by holin At January 07, 2009 12:33

Render in model

1
2
3
4
ActionView::Base.new(Rails::Configuration.new.view_path).render(
    :partial => "shared/someview",
    :locals => {:somevar => somevar}
)

>>发表评论

    Posted by devon At December 31, 2008 10:03

注册window onload事件

1
2
3
4
5
6
7
8
9
<script type="text/javascript" charset="utf-8">
Event.observe(window, 'load',
function() {
        alert('上传成功');
        parent.upload_call_back('<%= @photo.photo.url -%>');
        close_parent_wedgit_window();
}
);
</script>

>>发表评论

    Posted by holin At December 23, 2008 14:31

重载model的find方法

1
2
3
4
5
6
7
class LineItem < ActiveRecord::Base
  class << self
    def find(*args)
      self.with_scope(:find => {:order => 'added_at'}) { super }
    end
  end
end

>>发表评论

    Posted by devon At December 17, 2008 08:07

检查字符utf8编码

1
2
3
4
5
6
7
8
9
10
11
12
class String 
 def utf8?
    begin
      utf8_arr = self.unpack('U*')
      true if utf8_arr && utf8_arr.size > 0
    rescue
      false
    end
  end
end

'中文'.utf8?

>>发表评论

    Posted by devon At December 11, 2008 11:07

计算两个日期间有多少个工作日

1
2
3
4
5
6
7
d1 = Date.new( 2006, 12, 1 ) 

d2 = Date.new( 2007, 1, 15 )

weekdays = (d1..d2).reject { |d| [0,6].include? d.wday } 

weekdays.length

>>发表评论

    Posted by devon At December 04, 2008 22:05

add scope for each states

1
2
3
4
5
6
7
8
class User < ActiveRecord::Base
   STATES = [ 'pending', 'approved', 'denied' ]

   validates_inclusion_of :state, :in => STATES

   # Define a named scope for each state in STATES
   STATES.each { |s| named_scope s, :conditions => { :state => s } }
end

批量生成 named_scope.

>>发表评论

    Posted by michael At December 03, 2008 15:50

Render in model or backgroundrb

1
2
3
4
5
6
7
8
9
class PaperJsView < ActionView::Base
  attr_accessor :questions, :scores
end

view = PaperJsView.new(Rails::Configuration.new.view_path)
view.questions = questions
view.scores = scores

s = view.render(:partial => "subjects/papers/paper.js.erb") 

>>发表评论

    Posted by holin At November 25, 2008 14:29

合并 conditions

1
2
3
4
5
6
7
8
9
10
@conditions = [] 
@con1 = params[:category] ? (@conditions << "company_categories.cat_name = '#{params[:category]}'") : nil 
@con2 = params[:alpha] ? (@conditions << "companies.name LIKE '#{params[:alpha]}%'") : nil 

# count the number of records returned with includes and conditions set 
@company_count = Company.count(:include => includes, :conditions => @conditions.join(" and ")) 

# Finally, our find 
@companies = Company.paginate :page => params[:page], :per_page => 10, :order => 'name', :include => includes, :conditions => @conditions.join(" and ") 

@conditions = []
@conditions << xx if xx
:conditions => @conditions.join(" and ")

>>发表评论

    Posted by devon At October 25, 2008 19:19

复制文件并去除特殊字符文件名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
require 'find'
require 'fileutils'

def dir_move( target,dirpath=Dir.pwd)
    ## check if path valid
    if !File.directory?(dirpath)  
        puts "error first path"
        return
    elsif File.file?(target)
        puts "error :target is a file exist"
        return
    end
    ###
    Dir.mkdir target unless File.exist? target
    Find.find dirpath do |path|
        path_lite=path.gsub(dirpath,'')
        target_path=(target+path_lite).gsub(/[^a-zA-Z0-9\.\-\+_\(\)\/]/,"_").gsub(/(__)+/,"zhongwen")
        begin
            if File.directory? path
                Dir.mkdir target_path
            else
                FileUtils.copy path,target_path
            end
        rescue
            # if type(path) != type(target_path)
            #            puts "waring: type unmatch, local=>#{path} is a #{type(path)},target=>#{target_path} is a #{type(target_path)}"
            #            end
        end
    end
    puts "everyting is ok"
end

def type(file)
    return unless File.exist? file
    if File.file? file
        "file"
    else
        "directory"
    end
end

dir_move("/Users/holin/bin2", "/Users/holin/bin")

>>发表评论

    Posted by holin At October 15, 2008 16:54

项目文件行数计算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
##
##  this is design for calculate the totals line of code in your project
##  version 1 @october 8th,2008 
##
 

module Enumerable
  # function to get total lines for file
  def total_lines
    lines = 0
    each_with_index {|content,lines|}
    return lines+1
  end
end


class CheckLines
  require 'find'


  @check_type = %w{txt rb erb yml html css xml}
  def initialize(directory)
    @total_lines = 0
    if  File.directory?(directory)
          @directory = directory 
          @contents = {}
          self.go
    else puts "#{directory} is not a directory! check it out!" and return
    end
  end
  
  def go
    if @directory
      Find.find @directory do |path|
        pathlite = path.gsub(@directory,'')
        if File.file? path
          File.open path do |f|
              tmp_line = f.total_lines  
             @contents.store(pathlite,tmp_line) 
             @total_lines += tmp_line
          end
        end
      end
      puts @total_lines
    end
  end
  
  def details
    @contents.each do |key,value|
      puts "#{key} file has lines of #{value}"
    end
  end
end

上课前临时写的,回来加强。

>>发表评论

    Posted by xhan At October 08, 2008 09:15

sanitizer html in controller

1
2
3
4
5
sanitizer = HTML::FullSanitizer.new
sanitizer.sanitize("<p>This <u>is<u> a <a href='test.html'><strong>test</strong></a>.</p>")

sanitizer = HTML::LinkSanitizer.new
sanitizer.sanitize("<a href='almost'>on my mind</a>\n<A href='almost'>all day long</A>")

>>发表评论

    Posted by devon At September 26, 2008 18:14

twitter风格的url

1
2
3
4
5
twitter风格的url, http://xxx.com/devon
map.connect ':name', :controller => 'user', :action => 'show'

route所有path到某一个action
map.connect '*path' , :controller => 'blog' , :action => 'unrecognized'

放到routes.rb的最后

>>发表评论

    Posted by devon At September 18, 2008 09:50

定位在浏览器窗口右边

1
2
3
4
5
6
7
8
9
function fixed_to_right(element, top) {
        this.move_score_show = function(){
                var arr = document.viewport.getScrollOffsets();
                var x = arr[0];
                var y = arr[1] + top;
                element.setStyle({top: y + "px"});
        }
        new PeriodicalExecuter(this.move_score_show, 0.1);
}

<span style="position: absolute; border: 1px solid; width: 110px; background-color: #f8f8f8; right: 10px;" id="score_<%= @exam_user.id -%>"><%= render :partial => "score", :object => @exam_user %></span>

>>发表评论

    Posted by holin At September 16, 2008 02:10

ruby通过XMPP发送及时信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
require 'xmpp4r'
   
class Messager
    
    def initialize
        puts 'initialize'
        #Jabber::debug = true
        jid = Jabber::JID.new('alexys.cn@gmail.com')
        @client = Jabber::Client.new(jid)
        @client.connect
        @client.auth('×××××')
        @client.send(Jabber::Presence.new.set_show(:chat).set_status('Rails!'))
    end

    def send(addr ,msg)
        sendto = addr       
        #to = 'hlxwell@gmail.com'
        subject = "Kuxue task"
        msgbody = msg
        mail = Jabber::Message::new(sendto, msgbody).set_type(:normal).set_id('1').set_subject(subject)
        @client.send mail
    end

end
a=Messager.new()
a.send("xhan87@gmail.com",'hello ,I am the bot')

>>发表评论

    Posted by xhan At August 26, 2008 14:54

自定义attachment_fu插件上传的文件名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class QuestionAttachment < ActiveRecord::Base
  belongs_to :question

  has_attachment :content_type => :image,
  :storage => :file_system, 
  :path_prefix => 'public/question_files'

  def sanitize_filename(filename)
    return unless filename
    returning filename.strip do |name| 

      name.gsub! /^[^\.]+/, 'customed filename'
    end
  end
end

直对单个后缀的文件有用,对xxx.tar.gz型文件名需要修改
name.gsub! /^[^\.]+/, 'customed filename'

>>发表评论

    Posted by holin At August 14, 2008 02:15

RUBY写的 目录及文件复制代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
require 'find'
require 'fileutils'
   
#   usage:   dir_move target-path (,local-path )
#   it will creat a directory if target-path is empty
#   TODO: add a option for u to choose whether replace everyting 
#   if local and target has same name but not the same type(file,directory)

def dir_move( target,dirpath=Dir.pwd)
    ## check if path valid
    if !File.directory?(dirpath)  
        puts "error first path"
        return
    elsif File.file?(target)
        puts "error :target is a file exist"
        return
    end
    ###
    Dir.mkdir target unless File.exist? target
    Find.find dirpath do |path|
        path_lite=path.gsub(dirpath,'')
        target_path=target+path_lite
        begin
            if File.directory? path
               Dir.mkdir target_path
            else
                FileUtils.copy path,target_path
            end
        rescue
            if type(path) != type(target_path)
            puts "waring: type unmatch, local=>#{path} is a #{type(path)},target=>#{target_path} is a #{type(target_path)}"
            end
        end
    end
    puts "everyting is ok"
end

def type(file)
    return unless File.exist? file
    if File.file? file
        "file"
    else
        "directory"
    end
end

没怎么严格测试。嘿嘿

>>发表评论

    Posted by xhan At August 13, 2008 17:56

代码验证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Application.rb中:

def rescue_action(exception) 
  exception.is_a?(ActiveRecord::RecordInvalid) ? render_invalid_record(exception.record)  
end 
def render_invalid_record(record) 
  @invalid_record = record 
  respond_to do |format| 
    format.html do 
      render :action => (record.new_record? ? 'new' : 'edit') 
    end 
    format.js do 
      render :update do |page| 
        page.alert @invalid_record.errors.full_messages.join("\n") 
      end 
    end 
  end 
end

controller中:
def create 
  #... 
  @news.save! 
  redirect_to news_path(@news) 
end

>>发表评论

    Posted by devon At July 28, 2008 09:04

flash消息,4秒后消失

1
2
3
4
5
6
7
8
<% if flash[:warning] or flash[:notice] %>  
  <div id="flash_message" <% if flash[:warning] %>class="warning"<% elsif flash[:notice] %>class='notice'<% end %> >  
    <%= flash[:warning] || flash[:notice] %>  
  </div>  
  <script type="text/javascript">  
    setTimeout("new Effect.Fade('flash_message');", 4000)  
  </script>  
<% end %>  

>>发表评论

    Posted by devon At July 25, 2008 17:10

rake task: 更改rhtml为html.erb

1
2
3
4
5
6
7
8
namespace 'views' do
  desc 'Renames all your rhtml views to erb'
  task 'rename' do
    Dir.glob('app/views/**/*.rhtml').each do |file|
      puts `svn mv #{file} #{file.gsub(/\.rhtml$/, '.html.erb')}`
    end
  end
end

>>发表评论

    Posted by devon At July 13, 2008 00:23

Benchmark 代码效率

1
2
3
4
5
6
7
8
9
10
11
require 'benchmark'
 
n = 100000
Benchmark.bm do |x|
   x.report('copy') { n.times do ; h = {}; h = h.merge({1 => 2}); end }
   x.report('no copy') { n.times do ; h = {}; h.merge!({1 => 2}); end }
end
 
#          user        system      total        real
# copy     0.460000   0.180000   0.640000 (  0.640692)
# no copy  0.340000   0.120000   0.460000 (  0.463339)

>>发表评论

    Posted by devon At July 11, 2008 09:19

include多对多关系


Exam.paginate :conditions=> ["users.id = ?", @user_id], :page => params[:page], :include => {:exam_users => :user}

>>发表评论

    Posted by holin At June 28, 2008 16:01

mongrel重启时清除过期的pid_file

1
2
3
4
5
6
7
8
9
10
11
12
13
if File.exist? defaults[:pid_file]
  # mongrels that crash can leave stale PID files behind, and these
  # should not stop mongrel from being restarted by monitors...
  pid = File.new(defaults[:pid_file]).readline
  unless `ps -ef | grep #{pid} | grep -v grep`.length > 0
    # use "ps ax" for freebsd 
    log "!!! PID file #{defaults[:pid_file]} exists, but is stale, and will be deleted so that this mongrel can run."
    File.delete(defaults[:pid_file])
  else
    log "!!! PID file #{defaults[:pid_file]} already exists and the process id referred to in it is running.  This mongrel is probably already running.  #{defaults[:log_file]} for errors.  EXITING."
    exit 1
  end
end

/usr/local/lib/ruby/gems/1.8/gems/mongrel-x.x.x/bin/mongrel_rails

>>发表评论

    Posted by devon At June 27, 2008 15:41

保留二级域名

1
2
3
4
class Account < ActiveRecord::Base
  ReservedSubdomains = %w[admin blog dev ftp mail pop pop3 imap smtp stage stats status www]
  validates_exclusion_of :subdomain, :in => ReservedSubdomains, :message => 'is not allowed'
end

>>发表评论

    Posted by devon At June 25, 2008 09:51

will_paginate with ajax

1
2
3
4
5
6
7
8
9
10
11
12
# helpers/remote_link_renderer.rb

class RemoteLinkRenderer < WillPaginate::LinkRenderer
  def page_link_or_span(page, span_class = 'current', text = nil)
    text ||= page.to_s
    if page and page != current_page
      @template.link_to_remote text, :url => url_for(page), :method => :get
    else
      @template.content_tag :span, text, :class => span_class
    end
  end
end

<%= will_paginate @photos, :renderer => 'RemoteLinkRenderer' %>

>>发表评论

    Posted by devon At June 13, 2008 14:44

Rails中用YML配置项目

1
2
3
4
5
6
7
8
9
10
11
12
# 在config/initializers中新增文件 app_config.rb

module ApplicationConfiguration
  require 'ostruct'
  require 'yaml'
  if File.exists?( File.join(RAILS_ROOT, 'config', 'application.yml') )
    file = File.join(RAILS_ROOT, 'config', 'application.yml')
    users_app_config = YAML.load_file file
  end

  ::AppConfig = OpenStruct.new users_app_config
end

然后,在config中增加application.yml,在里面以YML方式写入配置,比如:
hello: ‘world’

则,在程序中,可以直接引用: AppConfig.hello。也可以在程序中对配置项赋值,比如 AppConfig.hello = ‘cool’

>>发表评论

    Posted by devon At June 12, 2008 14:07

url escape

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
require 'uri'
require 'cgi'

foo = "http://google.com?query=hello"

uri_good = URI.escape(foo, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
cgi_good = CGI.escape(foo)




require 'uri'
foo = "http://google.com?query=hello"

bad = URI.escape(foo)
good = URI.escape(foo, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))

bad_uri = "http://mysite.com?service=#{bad}&bar=blah"
good_uri = "http://mysite.com?service=#{good}&bar=blah"

puts bad_uri
# outputs "http://mysite.com?service=http://google.com?query=hello&bar=blah"

puts good_uri
# outputs "http://mysite.com?service=http%3A%2F%2Fgoogle.com%3Fquery%3Dhello&bar=blah"

>>发表评论

    Posted by devon At June 11, 2008 12:45

in_place_editor_field: 空值时的处理方式之一

1
2
<span id="name_<%= @student.id %>">Name:</span>
<%= in_place_editor_field :student, :name, {}, :external_control => "name_#{@student.id}" %>

其它方案:

http://d.hatena.ne.jp/zariganitosh/20070613

http://script.aculo.us/docs/Ajax.InPlaceEditor.html

http://seb.box.re/2008/2/3/patch-for-inplaceeditor-adding-editonblank-feature

>>发表评论

    Posted by devon At May 21, 2008 11:11