2011-03-27 1 views
1

내 블로그의 '아카이브'페이지를 만들려고합니다. 월별로 그룹화 된 역순으로 만성적으로 모든 블로그 제목을 나열해야합니다.블로그 게시물의 월간 아카이브 표시

저는 MySQL과 같은 DATE_FORMAT 함수가없는 DataMapper를 사용하고 있습니다. 이는 단순히 쿼리 내에서 그룹화 할 수 없다는 것을 의미합니다. 그러므로 나는 루비의 모든 노력을하는 것 외에 다른 방법을 찾지 못한다.

내가 현재 가지고있는 것입니다 :

# GOOD: order of posts within the months are correct 
# BAD: order of months is random 

@posts = Post.published(:order => :published_at.desc) 

@months = {} 
@posts.each do |post| 
    month_year = post.published_at.strftime("%B %Y") 
    @months[month_year] = [] unless @months.has_key? month_year 
    @months[month_year] << post 
end 

보기 :

.archive 
    - @months.each do |month, posts| 
    %h2= month 
    %ol 
     - posts.each do |post| 
     = partial(post) 

이 나는 ​​그들이가 해시에 포함되어 있기 때문에 달의 순서가 엉망 제외하고 원하는 것을. (저는 해시 순서가 무작위이므로 Ruby 1.8을 사용하고 있습니다).

어떻게 달의 순서를 바꿀 수 있습니까? 대신 아마 배열을 사용할 필요가 있지만 나머지 코드는 어떻게 생겼는지 알 수 없습니다.

답변

1
# Creating random data to similate your DataMapper array 
require 'date' 
require 'ostruct' 

posts = 10.times.inject([]) {|s,i| s << OpenStruct.new(:id => i, :published_at => Date.parse("2010-#{rand(11)+1}-#{rand(25)+1}"), :title => "title #{i}")} 

# Your code starts here 
ordered_posts = posts.inject({}) do |s,p| 
    ym = p.published_at.strftime('%Y-%m') 
    s.merge(s[ym] ? {ym=>s[ym]<<p} : {ym=>[p]}) 
end.sort {|a,b| b[0] <=> a[0]} 

# then in your view do 
ordered_posts.each do |op| 
    puts op[0][-2,2] # your %h2 line 
    op[1].sort {|a,b| b.published_at <=> a.published_at}.each do |p| 
    puts " #{p.published_at.strftime('%m/%d/%y')}-#{p.title}" # your partial(posts) line 
    end 
end 

가 생성됩니다

[email protected]:~/code_katas> ruby blogs.rb 
11 
    11/10/10-title 9 
10 
    10/21/10-title 2 
09 
    09/17/10-title 8 
08 
    08/21/10-title 1 
    08/06/10-title 3 
07 
    07/06/10-title 6 
06 
    06/07/10-title 5 
05 
    05/12/10-title 7 
03 
    03/16/10-title 4 
01 
    01/17/10-title 0 
+0

감사합니다, 그 일을! – Marc

0
# posts_controller 
@months = @posts.group_by { |post| post.published_at.strftime("%B %Y")} 

# archive view 
.archive 
    - @months.each do |month, posts| 
    %h2= month 
    %ol 
     = render posts 
+0

나는 당신의 코드를 시험해 보았다. 그러나 어떤 이유로 몇 달 동안은 group_by가 아무런 영향을 미치지 않는 것처럼 무작위 순서로 겉으로보기에 여전히 있었다. – Marc