Class: Post

Inherits:
Object
  • Object
show all
Defined in:
lib/post.rb

Constant Summary collapse

NEW_MARKER =
"imported_by:gourmand"
Data =
:url, :dt, :description, :extended, :tags

Instance Method Summary collapse

Constructor Details

#initialize(hash = nil) {|_self| ... } ⇒ Post

Returns a new instance of Post.

Yields:

  • (_self)

Yield Parameters:

  • _self (Post)

    the object that the method was called on



14
15
16
17
18
19
20
21
22
# File 'lib/post.rb', line 14

def initialize(hash=nil)    
  yield self if block_given?        
  if hash
    hash.each do |key, value|
      instance_variable_set("@" + key.to_s, value)
    end
  end        
  raise "all posts must have a URL" if !self.url  
end

Instance Method Details

#==(that) ⇒ Object



49
50
51
52
53
54
55
56
# File 'lib/post.rb', line 49

def ==(that)
  (that.is_a?(Post) && 
  (self.url == that.url) &&
  (self.description == that.description) &&
  (self.extended == that.extended) &&
  (self.dt == that.dt) && 
  (self.tag_set == that.tag_set)) || false
end

#auto_imported?Boolean

Returns:

  • (Boolean)


30
31
32
# File 'lib/post.rb', line 30

def auto_imported?
  tag_set.include?(NEW_MARKER)
end

#dupObject



58
59
60
# File 'lib/post.rb', line 58

def dup
  Post.new(self.to_h)
end

#fetch_metadata!Object



38
39
40
41
42
43
44
45
46
47
# File 'lib/post.rb', line 38

def fetch_metadata!()        
  self.description ||= begin      
    Nokogiri::HTML(open(url)).xpath("//title").text.gsub("\n", " ").gsub(/ +/, " ").strip 
  rescue Exception => e
    puts "WARNING: #{e}"
    url
  end
  
  self.description = url if description.empty?
end

#merge(that) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/post.rb', line 62

def merge(that)
  return self if that.nil?
  raise "cannot merge posts with different URLS: #{self.url} != #{that.url}" if self.url != that.url

  result = Post.new{|p| 
    p.url = self.url
    p.description = that.description

    if(self.extended && !that.extended)
      p.extended = self.extended 
    else
      p.extended = that.extended
    end

    old_tags = that.tag_set 
    new_tags = self.tag_set - old_tags
    
    # remove the new marker unless it was already present in old post
    new_tags -= [NEW_MARKER] unless that.auto_imported?
    
    p.tags = if !new_tags.empty? 
      new_tags.to_a.join(" ") + " " + that.tags
    else
      that.tags
    end

    p.dt = [self.dt, that.dt].compact.min  
  }
  
  result = nil if result == that 
  result
end

#tag_setObject



34
35
36
# File 'lib/post.rb', line 34

def tag_set
  if !self.tags then Set.new else Set[*self.tags.split] end
end

#to_hObject



24
25
26
27
28
# File 'lib/post.rb', line 24

def to_h
  it = {}
  Data.each{|d| it[d] = instance_variable_get("@" + d.to_s)}
  it
end