OSDN Git Service

t#:
[laoz/laoz.git] / app / models / hateda_thema.rb
1 # はてなダイアリに突っ込む。
2 require 'erb'
3 class HatedaThema < ActiveRecord::Base
4   include ActionView::Helpers::TextHelper
5   include ActionView::Helpers::TagHelper
6   include ApplicationHelper
7   belongs_to :thema
8   
9   before_save :modify
10   
11   def modify
12     self.upload_at = Time.now if self.name
13   end
14   
15   def upload_time
16     if self.upload_at
17       self.upload_at.strftime('%Y/%m/%d %H:%M:%S')
18     else
19       nil
20     end
21   end
22   
23   def title(htn)
24     "[道徳経][テーマ]#{self.thema.caption}"
25   end
26   
27   def content(htn)
28     sections = Section.find(:all, :include => :thema_sections, 
29       :conditions => ['thema_sections.thema_id = ?', self.thema.id]
30     )
31     ERB.new(open(RAILS_ROOT + '/lib/hateda_thema.rhtml').read.untaint, nil, '-').result(binding)
32   end
33   
34   def self.upload(htn, ht)
35     if ht.name.to_s.empty?
36       entry = Atom::Entry.new(
37         :updated => Time.parse('2010/1/10') + (ht.thema.id - 1).day, 
38         :title => ht.title(htn), 
39         :content => ht.content(htn)
40       )
41       ht.name = htn.create(entry)
42     else
43       entry = htn.entry(ht.name)
44       entry.title = ht.title(htn)
45       entry.content = ht.content(htn)
46       htn.update(ht.name, entry)
47     end
48     ht.save!
49     sleep 3
50   end
51   
52   def self.remove(htn, ht)
53     begin
54       htn.destroy(ht.name)
55     end
56     ht.name = nil
57     ht.upload_at = nil
58     ht.save!
59   end
60   
61   def self.upload_one(un, pass, thema_id)
62     htn = Hatena.new(un, pass)
63     thema = Thema.find(thema_id)
64     self.upload(htn, thema.hateda_thema)
65   end
66   
67   def self.upload_modified(un, pass)
68     htn = Hatena.new(un, pass)
69     themas = Thema.find(:all, :include => [:hateda_thema], 
70       :conditions => ['hateda_themas.name is null or hateda_themas.upload_at < themas.update_at']
71     )
72     themas.each do |thema|
73       self.upload(htn, thema.hateda_thema)
74     end
75   end
76   
77   def self.remove_one(htn, thema_id)
78     thema = Thema.find(thema_id)
79     self.remove(htn, thema.hateda_thema)
80   end
81   
82   def self.remove_all(un, pass)
83     htn = Hatena.new(un, pass)
84     themas = Thema.find(:all, :include => [:hateda_thema], 
85       :conditions => ['hateda_themas.name is not null']
86     )
87     themas.each do |thema|
88       self.remove(htn, thema.hateda_thema)
89     end
90   end
91   
92 end