Class: Piwik::Base

Inherits:
Object
  • Object
show all
Includes:
ApiScope, Typecast
Defined in:
lib/piwik/base.rb

Direct Known Subclasses

ApiModule, ApiResponse, Site, User

Constant Summary collapse

@@template =
<<-EOF
# .piwik
# 
# Please fill in fields like this:
#
#  piwik_url: http://your.piwik.site
#  auth_token: secret
#
piwik_url: 
auth_token: 
EOF

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ApiScope

included

Methods included from Typecast

included

Constructor Details

#initialize(params = {}) ⇒ Base

Returns a new instance of Base.


32
33
34
35
36
37
# File 'lib/piwik/base.rb', line 32

def initialize params = {}
  @attributes = OpenStruct.new
  params.map do |k,v|
    @attributes.send(:"#{k}=",typecast(v))
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object

delegate attribute calls to @attributes storage


93
94
95
96
97
98
99
# File 'lib/piwik/base.rb', line 93

def method_missing(method,*args,&block)
  if self.attributes.respond_to?(method)
    self.attributes.send(method,*args,&block)
  else
    super
  end
end

Instance Attribute Details

#attributesObject

common constructor, using ostruct for attribute storage


31
32
33
# File 'lib/piwik/base.rb', line 31

def attributes
  @attributes
end

Class Method Details

.call(method, params, piwik_url = nil, auth_token = nil) ⇒ Object

Calls the supplied Piwik API method, with the supplied parameters.

Returns a string containing the XML reply from Piwik, or raises a Piwik::ApiError exception with the error message returned by Piwik in case it receives an error.


142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/piwik/base.rb', line 142

def call(method, params, piwik_url=nil, auth_token=nil)
  params ||= {}
  raise MissingConfiguration, "Please edit ~/.piwik to include your piwik url and auth_key" if piwik_url.nil? || auth_token.nil?
  url = "#{piwik_url}/index.php?"
  params.merge!({:module => 'API', :format => 'xml', :method => method})
  params.merge!({:token_auth => auth_token}) unless auth_token.nil?
  url << params.map { |k, v| "#{k}=#{CGI.escape(v.to_s)}" }.join('&')
  verbose_obj_save = $VERBOSE
  $VERBOSE = nil # Suppress "warning: peer certificate won't be verified in this SSL session"
  xml = RestClient.get(url)
  $VERBOSE = verbose_obj_save
  if xml.is_a?(String) && xml.force_encoding('BINARY').is_binary_data?
    xml.force_encoding('BINARY')
  elsif xml =~ /error message=/
    result = XmlSimple.xml_in(xml, {'ForceArray' => false})
    raise ApiError, result['error']['message'] if result['error']
  else
    xml
  end
end

.collectionObject


121
122
123
# File 'lib/piwik/base.rb', line 121

def collection
  "#{self.to_s.pluralize}".safe_constantize
end

.load(id) ⇒ Object Also known as: reload


132
133
134
# File 'lib/piwik/base.rb', line 132

def load id
  collection.get(id_attr => id)
end

.load_config_from_fileObject

Checks for the config, creates it if not found


164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/piwik/base.rb', line 164

def load_config_from_file  # Useful for testing or embedding credentials - although as always 
  # it is not recommended to embed any kind of credentials in source code for security reasons

  return { :piwik_url => PIWIK_URL, :auth_token => PIWIK_TOKEN } if PIWIK_URL.present? and PIWIK_TOKEN.present?
  config = {}
  if defined?(RAILS_ROOT) and RAILS_ROOT != nil
    home =  RAILS_ROOT
    filename = "config/piwik.yml"
  else
    home =  ENV['HOME'] || ENV['USERPROFILE'] || ENV['HOMEPATH'] || "."
    filename = ".piwik"
  end
  temp_config = if File.exists?(File.join(home,filename))
    YAML::load(open(File.join(home,filename)))
  else
    open(File.join(home,filename),'w') { |f| f.puts @@template }
    YAML::load(@@template)
  end
  temp_config.each { |k,v| config[k.to_sym] = v } if temp_config
  if config[:piwik_url] == nil || config[:auth_token] == nil
    if defined?(RAILS_ROOT) and RAILS_ROOT != nil
      raise MissingConfiguration, "Please edit ./config/piwik.yml to include your piwik url and auth_key"
    else
      raise MissingConfiguration, "Please edit ~/.piwik to include your piwik url and auth_key"
    end

  end
  config
end

.parse_xml(xml) ⇒ Object

This is required to normalize the API responses when the Rails XmlSimple version is used


126
127
128
129
130
# File 'lib/piwik/base.rb', line 126

def parse_xml xml
  result = XmlSimple.xml_in(xml, {'ForceArray' => false})
  result = result['result'] if result['result']
  result
end

Instance Method Details

#call(method, params = {}) ⇒ Object

Calls the supplied Piwik API method, with the supplied parameters.

Returns a string containing the XML reply from Piwik, or raises a Piwik::ApiError exception with the error message returned by Piwik in case it receives an error.


108
109
110
# File 'lib/piwik/base.rb', line 108

def call(method, params={})
  self.class.call(method, params, config[:piwik_url], config[:auth_token])
end

#collectionObject


116
117
118
# File 'lib/piwik/base.rb', line 116

def collection
  self.class.collection
end

#configObject


112
113
114
# File 'lib/piwik/base.rb', line 112

def config
  @config ||= self.class.load_config_from_file
end

#created_atObject

created_at will try and return the value of the Piwik item id if it exists


88
89
90
# File 'lib/piwik/base.rb', line 88

def created_at
  attributes.send(:ts_created) rescue nil
end

#deleteObject Also known as: destroy


55
56
57
# File 'lib/piwik/base.rb', line 55

def delete
  collection.delete(attributes)
end

#idObject

id will try and return the value of the Piwik item id if it exists


75
76
77
78
79
80
81
82
83
84
85
# File 'lib/piwik/base.rb', line 75

def id
  begin
    if self.class == Piwik::Site
      self.idsite
    else
      attributes.send(:"id#{self.class.to_s.gsub('Piwik::','')}")
    end
  rescue Exception => e
    $stderr.puts e
  end
end

#id_attrObject


39
40
41
# File 'lib/piwik/base.rb', line 39

def id_attr
  self.class.id_attr
end

#new?Boolean

Returns true if the current site does not exists in the Piwik yet.

Returns:

  • (Boolean)

61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/piwik/base.rb', line 61

def new?
  begin
    if respond_to?(:id)
      id.nil? && created_at.blank?
    else
      created_at.blank?
    end
    
  rescue Exception => e
    nil
  end
end

#parse_xml(xml) ⇒ Object


101
# File 'lib/piwik/base.rb', line 101

def parse_xml xml; self.class.parse_xml xml; end

#saveObject Also known as: update


43
44
45
46
47
48
49
50
51
52
# File 'lib/piwik/base.rb', line 43

def save
  if new?
    resp = collection.add(attributes)
    attributes = resp.attributes
    true
  else
    collection.save(attributes)
  end
  
end