Class: WordPress::Post::Meta

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

Instance Method Summary collapse

Methods inherited from Base

#get_post_meta, #get_the_terms, #insert, #set_post_meta, #set_post_terms, #update, #update_or_insert

Constructor Details

#initialize(root, post) ⇒ Meta

Returns a new instance of Meta.



7
8
9
10
# File 'lib/wordpress/post/meta.rb', line 7

def initialize root, post
  super root
  @post = post
end

Instance Method Details

#[](key) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/wordpress/post/meta.rb', line 12

def [](key)
  v = nil
  @conn.query("SELECT `meta_value` FROM `#{@tbl[:postmeta]}` WHERE `meta_key`='#{@conn.escape key}' AND `post_id`='#{ @post.post_id.to_i }' LIMIT 1").each do |row|
    v = row[:meta_value]
  end
  # Apply out-filters
  if v
    if v[0, 1] == 'a' and v[-1, 1] == '}'
      # PHP-serialized array
      v = PHP.unserialize v
    end
  end
  v
end

#[]=(key, value) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/wordpress/post/meta.rb', line 27

def []=(key, value)
  old_value = self[key]
  # Apply in-filters

  if value.kind_of?(Hash) or value.kind_of?(Array)
    value = PHP.serialize value
  end

  if !value.nil? and !old_value.nil? and value != old_value
    # Update operation.
    @conn.query("UPDATE `#{@tbl[:postmeta]}` SET `meta_value`='#{@conn.escape value.to_s}' WHERE `meta_key`='#{@conn.escape key}' AND `post_id`='#{ @post.post_id.to_i }'")
  elsif value.nil? and !old_value.nil?
    # New value nil, old value not. Delete operation.
    @conn.query("DELETE FROM `#{@tbl[:postmeta]}` WHERE `meta_key`='#{@conn.escape key}' AND `post_id`='#{ @post.post_id.to_i }'")
  elsif !value.nil? and old_value.nil?
    # New value non-nil, old value nil. Insert operation.
    @conn.query("INSERT INTO `#{@tbl[:postmeta]}` (`meta_key`, `meta_value`, `post_id`) VALUES ('#{@conn.escape key}', '#{@conn.escape value.to_s}', '#{ @post.post_id.to_i }')")
  end
  value
end

#keysObject



48
49
50
51
52
# File 'lib/wordpress/post/meta.rb', line 48

def keys
  all = []
  @conn.query("SELECT `meta_key` FROM `#{@tbl[:postmeta]}` WHERE `post_id`='#{ @post.post_id.to_i }'").each { |x| all << x }
  all.collect { |x| x[:meta_key] }
end

#to_hObject Also known as: to_hash, inspect



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

def to_h
  Hash[keys.map { |e| [e, self[e]] }]
end

#to_sObject



54
55
56
# File 'lib/wordpress/post/meta.rb', line 54

def to_s
  to_h.to_s
end