Class: AsanaExceptionNotifier::ErrorPage

Inherits:
Object
  • Object
show all
Includes:
ApplicationHelper
Defined in:
lib/asana_exception_notifier/classes/error_page.rb

Overview

class used for rendering the template for exception

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from ApplicationHelper

add_files_to_zip, archive_files, ensure_thread_running, escape, execute_with_rescue, expanded_path, extract_body, force_utf8_encoding, get_extension_and_name_from_file, get_hash_rows, get_table_headers, get_table_rows, hash_to_html_attributes, inspect_value, log_bactrace, log_exception, logger, mount_table_for_hash, path_is_a_template?, permitted_options, prepare_archive_creation, rails_logger, remove_blank, rescue_interrupt, root, run_new_thread, set_fieldset_key, split_archive, tempfile_details, template_dir, template_path_exist

Methods included from HeredocHelper

link_helper, mount_table

Constructor Details

#initialize(template_path, exception, options) ⇒ void

Initializes the instance with the template path that will be used to render the template, the exception caught by the middleware and additional options sent by the middleware

Parameters:

  • template_path (String)

    The template_path that will be used to render the exception details

  • exception (Exception)

    The exception that was caught by the middleware

  • options (Hash)

    Additional options that the middleware can send ( Default : {})

See Also:



39
40
41
42
43
44
45
46
47
48
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 39

def initialize(template_path, exception, options)
  @exception = exception
  @options = options.symbolize_keys
  html_template(template_path)
  @template_details = setup_template_details
  @env = (@options[:env] || ENV.to_h).stringify_keys
  @request = action_dispatch? ? ActionDispatch::Request.new(@env) : Rack::Request.new(@env)
  @timestamp = Time.now
  parse_exception_options
end

Instance Attribute Details

#envHash (readonly)

Returns The environment that was sent by the middleware or the ENV variable.

Returns:

  • (Hash)

    The environment that was sent by the middleware or the ENV variable



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 23

class ErrorPage
  include AsanaExceptionNotifier::ApplicationHelper

  attr_reader :template_path, :exception, :options, :template_details, :env, :request, :tempfile, :template_params

  # Initializes the instance with the template path that will be used to render the template,
  # the exception caught by the middleware and additional options sent by the middleware
  # @see #html_template
  # @see #setup_template_details
  # @see #parse_exception_options
  #
  # @param [String] template_path The template_path that will be used to render the exception details
  # @param [Exception] exception The exception that was caught by the middleware
  # @param [Hash] options Additional options that the middleware can send ( Default : {})
  #
  # @return [void]
  def initialize(template_path, exception, options)
    @exception = exception
    @options = options.symbolize_keys
    html_template(template_path)
    @template_details = setup_template_details
    @env = (@options[:env] || ENV.to_h).stringify_keys
    @request = action_dispatch? ? ActionDispatch::Request.new(@env) : Rack::Request.new(@env)
    @timestamp = Time.now
    parse_exception_options
  end

  # Initializes the instance with the template path that will be used to render the template,
  # the exception caught by the middleware and additional options sent by the middleware
  # @see #path_is_a_template
  # @see #expanded_path
  # @see #template_dir
  #
  # @param [String] path The template_path that will be used to render the exception details
  #
  # @return [void]
  def html_template(path)
    @template_path = if path_is_a_template?(path)
                       expanded_path(path)
                     else
                       File.join(template_dir, 'exception_details.html.erb')
                     end
  end

  # Returns true or false if ActionDispatch is available
  #
  # @return [Boolean] returns true if ActionDispatch::Request is defined, false otherwise
  def action_dispatch?
    defined?(ActionDispatch::Request)
  end

  # Gets the name and the extension of the template path, if was provided custom
  # ( this is needed in case someone wants something else than ERB template , since Tilt can support multiple formats)
  # @see #get_extension_and_name_from_file
  #
  # @return [Hash] Returns a hash containing the name and the extension of the template
  def setup_template_details
    template_extension = @template_path.scan(/\.(\w+)\.?(.*)?/)[0][0]
    get_extension_and_name_from_file(@template_path).merge(
      template_extension: template_extension
    )
  end

  # :reek:TooManyStatements: { max_statements: 10 }
  #
  # Fetches information about request, exception, environment and other additional information needed for the template
  # @see #fetch_basic_info
  # @see #exception_data
  # @see #setup_env_params
  # @see #filter_params
  # @see #session
  # @see #request_params
  # @see Rack::Request#cookies
  # @see ActionDispatch::Request#filtered_env
  # @see ActionDispatch::Request#filtered_parameters
  #
  # @return [Hash] Returns a hash containing all the information gathered about the exception, including env, cookies, session, and other additional information
  def parse_exception_options
    @template_params ||= {
      basic_info: fetch_basic_info,
      exception: @exception,
      request: @request,
      env: @request.respond_to?(:filtered_env) ? @request.filtered_env : @env,
      data: (@env.blank? ? {} : @env.fetch(:'exception_notifier.exception_data', {})).merge(@options[:data] || {}),
      exception_data: exception_data,
      request_data: setup_env_params,
      parameters: @request.respond_to?(:filtered_parameters) ? filter_params(@request.filtered_parameters) : filter_params(request_params),
      session: filter_params(session.respond_to?(:to_hash) ? session.to_hash : session.to_h),
      cookies: filter_params(@request.cookies.to_h)
    }.merge(@options).reject { |_key, value| value.blank? }
  end

  # returns the session from the request, (either from ActionDispatch or from Rack)
  #
  # @return [Hash] Returns the session of the request
  def session
    @request.session
  end

  # returns basic information about the system, like hostname, rails root directory, the process Id, the uname , the timestamp, and the Program name
  # @see Socket#gethostname
  # @see Rails::root
  # @see Sys::Uname#uname
  #
  # @return [Hash] Returns basic information about the system, like hostname, and other additionl information
  def fetch_basic_info
    {
      server:  Socket.gethostname,
      rails_root: defined?(Rails) ? Rails.root : nil,
      process: $PROCESS_ID,
      uname: Sys::Uname.uname,
      timestamp: @timestamp,
      pwd:  File.expand_path($PROGRAM_NAME)
    }
  end

  # returns information about the exception, like the class name, the message, the backtrace, the cause ( if gem 'cause' is used)
  #
  # @return [Hash] Returns information about the exception, like the class name, the message, the backtrace, the cause ( if gem 'cause' is used)
  def exception_data
    exception_service.merge(
      error_class: @exception.class.to_s,
      message:  @exception.respond_to?(:message) ? @exception.message : exception.inspect,
      backtrace: @exception.respond_to?(:backtrace) ? (@exception.backtrace || []).join("\n") : nil,
      cause: @exception.respond_to?(:cause) ? @exception.cause : nil
    )
  end

  # returns the instance variables defined by the exception, useful when using custom exceptions
  #
  # @return [Hash] Returns information about the instance variables defined by the exception, useful when using custom exceptions
  def exception_service
    hash = {}
    @exception.instance_variables.select do |ivar|
      attr_value = @exception.instance_variable_get(ivar)
      hash[ivar.to_s] = attr_value if attr_value.present?
    end
    hash
  end

  # returns information about URL, referer, http_method used, ip address and user agent
  #
  # @return [Hash] Returns information about URL, referer, http_method used, ip address and user agent
  def setup_env_params
    {
      url: @request.respond_to?(:original_url) ? @request.original_url : @request.path_info,
      referrer: @request.referer,
      http_method: action_dispatch? ? @request.method : @request.request_method,
      ip_address:  @request.respond_to?(:remote_ip) ? @request.remote_ip : @request.ip,
      user_agent: @request.user_agent
    }
  end

  # Filters sensitive information from parameters so that they won't get leaked into the template
  # @see AsanaExceptionNotifier::UnsafeFilter#new
  #
  # @return [Hash] Returns the information filtered , by using custom filters or the default one
  def filter_params(params)
    AsanaExceptionNotifier::UnsafeFilter.new(params, @options.fetch(:unsafe_options, [])).arguments
  end

  # returns the params sent with the initial request
  #
  # @return [Hash] Returns the params sent with the initial request
  def request_params
    @request.params
  rescue
    {}
  end

  # returns the names that will be used on the table header in the template
  # @see #fieldsets
  # @see #link_helper
  #
  # @return [String] returns the names that will be used on the table header in the template
  def fieldsets_links
    fieldsets.map { |key, _value| link_helper(key.to_s) }.join(' | ')
  end

  # returns fieldsets that will be showned in the template on separate table
  # @see #mount_tables_for_fieldsets
  #
  # @return [Array<Hash>] returns fieldsets that will be showned in the template on separate table
  def fieldsets
    @fieldsets ||= mount_tables_for_fieldsets
    @fieldsets
  end

  # returns fieldsets that will be showned in the template on separate table
  # @see #fetch_fieldsets
  # @see #mount_table_for_hash
  #
  # @return [Hash] returns the tables that will be used to render on the template as a Hash
  def mount_tables_for_fieldsets
    hash = fetch_fieldsets
    hash.each do |key, value|
      html = mount_table_for_hash(value)
      hash[key] = html if html.present?
    end
    hash
  end

  # iterates over the template params and sets the fieldsets that will be will be displayed in tables
  # @see #set_fieldset_key
  #
  # @param [Hash] hash the hash that will contain the data will be displayed in tables
  #
  # @return [void]
  def build_template_params_hash(hash)
    @template_params.each_with_parent do |parent, key, value|
      next if value.blank? || key.blank?
      parent_name = set_fieldset_key(hash, parent, 'system_info')
      hash[parent_name][key] = value
    end
  end

  # builds the template params that wil be used to construct the fieldsets and sorts them alphabetically
  # @see #build_template_params_hash
  #
  # @param [Hash] hash the hash that will contain the template params that wil be used to construct the fieldsets sorted alphabetically
  #
  # @return [Hash] returns the hash that will contain the template params that wil be used to construct the fieldsets sorted alphabetically
  def fetch_fieldsets(hash = {})
    build_template_params_hash(hash)
    hash.keys.map(&:to_s).sort
    hash
  end

  # adds the fieldsets and the fieldsets_links to the template params
  # @see #fieldsets
  # @see #fieldsets_links
  #
  # @return [void]
  def setup_template_params_for_rendering
    @template_params[:fieldsets] = fieldsets
    @template_params[:fieldsets_links] = fieldsets_links
  end

  # renders the template or the default template with the template params
  # @see #execute_with_rescue
  # @see #setup_template_params_for_rendering
  #
  # @return [void]
  def render_template(template = nil)
    execute_with_rescue do
      current_template = template.present? ? template : @template_path
      setup_template_params_for_rendering
      Tilt.new(current_template).render(self, @template_params.stringify_keys)
    end
  end

  # Creates a archive from the render_template outpout and returns the filename and the path of the file
  # @see Tempfile#new
  # @see Tempfile#write
  # @see ObjectSpace#undefine_finalizer
  # @see Tempfile#close
  # @see #tempfile_details
  #
  # @return [Array<String>] returns an array containing the filename as first value, and the path to the tempfile created as second value
  def create_tempfile(output = render_template)
    tempfile = Tempfile.new([SecureRandom.uuid, ".#{@template_details[:template_extension]}"], encoding: 'utf-8')
    tempfile.write(output)
    ObjectSpace.undefine_finalizer(tempfile) # force garbage collector not to remove automatically the file
    tempfile.close
    tempfile_details(tempfile).slice(:filename, :path).values
  end

  # Executes the fetch_archives and returns the result or empty array in case of exception
  # @see #fetch_archives
  #
  # @return [Array] returns an array with file paths to the created archives
  def fetch_all_archives
    fetch_archives
  rescue
    []
  end

  # Creates the archive, compresses it , and then removes the temporary file and splits the archive if needed
  # @see #create_tempfile
  # @see #archive_files
  # @see #remove_tempfile
  # @see #split_archive
  #
  # @return [Array] returns an array with file paths to the created archives
  def fetch_archives(output = render_template)
    return [] if output.blank?
    filename, path = create_tempfile(output)
    archive = archive_files(File.dirname(path), filename, [expanded_path(path)])
    remove_tempfile(path)
    split_archive(archive, "part_#{filename}", 1024 * 1024 * 100) # 104_857_600
  end

  # If DEBUG_ASANA_TEMPLATE is present this method will only log the path , otherwise will remove the file.
  # @param [String] path The path of the Tempfile that needs to be removed or logged
  #
  # @return [void]
  def remove_tempfile(path)
    if ENV['DEBUG_ASANA_TEMPLATE']
      logger.debug(path)
    else
      FileUtils.rm_rf([path])
    end
  end
end

#exceptionHash (readonly)

Returns The exception that will be parsed.

Returns:

  • (Hash)

    The exception that will be parsed



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 23

class ErrorPage
  include AsanaExceptionNotifier::ApplicationHelper

  attr_reader :template_path, :exception, :options, :template_details, :env, :request, :tempfile, :template_params

  # Initializes the instance with the template path that will be used to render the template,
  # the exception caught by the middleware and additional options sent by the middleware
  # @see #html_template
  # @see #setup_template_details
  # @see #parse_exception_options
  #
  # @param [String] template_path The template_path that will be used to render the exception details
  # @param [Exception] exception The exception that was caught by the middleware
  # @param [Hash] options Additional options that the middleware can send ( Default : {})
  #
  # @return [void]
  def initialize(template_path, exception, options)
    @exception = exception
    @options = options.symbolize_keys
    html_template(template_path)
    @template_details = setup_template_details
    @env = (@options[:env] || ENV.to_h).stringify_keys
    @request = action_dispatch? ? ActionDispatch::Request.new(@env) : Rack::Request.new(@env)
    @timestamp = Time.now
    parse_exception_options
  end

  # Initializes the instance with the template path that will be used to render the template,
  # the exception caught by the middleware and additional options sent by the middleware
  # @see #path_is_a_template
  # @see #expanded_path
  # @see #template_dir
  #
  # @param [String] path The template_path that will be used to render the exception details
  #
  # @return [void]
  def html_template(path)
    @template_path = if path_is_a_template?(path)
                       expanded_path(path)
                     else
                       File.join(template_dir, 'exception_details.html.erb')
                     end
  end

  # Returns true or false if ActionDispatch is available
  #
  # @return [Boolean] returns true if ActionDispatch::Request is defined, false otherwise
  def action_dispatch?
    defined?(ActionDispatch::Request)
  end

  # Gets the name and the extension of the template path, if was provided custom
  # ( this is needed in case someone wants something else than ERB template , since Tilt can support multiple formats)
  # @see #get_extension_and_name_from_file
  #
  # @return [Hash] Returns a hash containing the name and the extension of the template
  def setup_template_details
    template_extension = @template_path.scan(/\.(\w+)\.?(.*)?/)[0][0]
    get_extension_and_name_from_file(@template_path).merge(
      template_extension: template_extension
    )
  end

  # :reek:TooManyStatements: { max_statements: 10 }
  #
  # Fetches information about request, exception, environment and other additional information needed for the template
  # @see #fetch_basic_info
  # @see #exception_data
  # @see #setup_env_params
  # @see #filter_params
  # @see #session
  # @see #request_params
  # @see Rack::Request#cookies
  # @see ActionDispatch::Request#filtered_env
  # @see ActionDispatch::Request#filtered_parameters
  #
  # @return [Hash] Returns a hash containing all the information gathered about the exception, including env, cookies, session, and other additional information
  def parse_exception_options
    @template_params ||= {
      basic_info: fetch_basic_info,
      exception: @exception,
      request: @request,
      env: @request.respond_to?(:filtered_env) ? @request.filtered_env : @env,
      data: (@env.blank? ? {} : @env.fetch(:'exception_notifier.exception_data', {})).merge(@options[:data] || {}),
      exception_data: exception_data,
      request_data: setup_env_params,
      parameters: @request.respond_to?(:filtered_parameters) ? filter_params(@request.filtered_parameters) : filter_params(request_params),
      session: filter_params(session.respond_to?(:to_hash) ? session.to_hash : session.to_h),
      cookies: filter_params(@request.cookies.to_h)
    }.merge(@options).reject { |_key, value| value.blank? }
  end

  # returns the session from the request, (either from ActionDispatch or from Rack)
  #
  # @return [Hash] Returns the session of the request
  def session
    @request.session
  end

  # returns basic information about the system, like hostname, rails root directory, the process Id, the uname , the timestamp, and the Program name
  # @see Socket#gethostname
  # @see Rails::root
  # @see Sys::Uname#uname
  #
  # @return [Hash] Returns basic information about the system, like hostname, and other additionl information
  def fetch_basic_info
    {
      server:  Socket.gethostname,
      rails_root: defined?(Rails) ? Rails.root : nil,
      process: $PROCESS_ID,
      uname: Sys::Uname.uname,
      timestamp: @timestamp,
      pwd:  File.expand_path($PROGRAM_NAME)
    }
  end

  # returns information about the exception, like the class name, the message, the backtrace, the cause ( if gem 'cause' is used)
  #
  # @return [Hash] Returns information about the exception, like the class name, the message, the backtrace, the cause ( if gem 'cause' is used)
  def exception_data
    exception_service.merge(
      error_class: @exception.class.to_s,
      message:  @exception.respond_to?(:message) ? @exception.message : exception.inspect,
      backtrace: @exception.respond_to?(:backtrace) ? (@exception.backtrace || []).join("\n") : nil,
      cause: @exception.respond_to?(:cause) ? @exception.cause : nil
    )
  end

  # returns the instance variables defined by the exception, useful when using custom exceptions
  #
  # @return [Hash] Returns information about the instance variables defined by the exception, useful when using custom exceptions
  def exception_service
    hash = {}
    @exception.instance_variables.select do |ivar|
      attr_value = @exception.instance_variable_get(ivar)
      hash[ivar.to_s] = attr_value if attr_value.present?
    end
    hash
  end

  # returns information about URL, referer, http_method used, ip address and user agent
  #
  # @return [Hash] Returns information about URL, referer, http_method used, ip address and user agent
  def setup_env_params
    {
      url: @request.respond_to?(:original_url) ? @request.original_url : @request.path_info,
      referrer: @request.referer,
      http_method: action_dispatch? ? @request.method : @request.request_method,
      ip_address:  @request.respond_to?(:remote_ip) ? @request.remote_ip : @request.ip,
      user_agent: @request.user_agent
    }
  end

  # Filters sensitive information from parameters so that they won't get leaked into the template
  # @see AsanaExceptionNotifier::UnsafeFilter#new
  #
  # @return [Hash] Returns the information filtered , by using custom filters or the default one
  def filter_params(params)
    AsanaExceptionNotifier::UnsafeFilter.new(params, @options.fetch(:unsafe_options, [])).arguments
  end

  # returns the params sent with the initial request
  #
  # @return [Hash] Returns the params sent with the initial request
  def request_params
    @request.params
  rescue
    {}
  end

  # returns the names that will be used on the table header in the template
  # @see #fieldsets
  # @see #link_helper
  #
  # @return [String] returns the names that will be used on the table header in the template
  def fieldsets_links
    fieldsets.map { |key, _value| link_helper(key.to_s) }.join(' | ')
  end

  # returns fieldsets that will be showned in the template on separate table
  # @see #mount_tables_for_fieldsets
  #
  # @return [Array<Hash>] returns fieldsets that will be showned in the template on separate table
  def fieldsets
    @fieldsets ||= mount_tables_for_fieldsets
    @fieldsets
  end

  # returns fieldsets that will be showned in the template on separate table
  # @see #fetch_fieldsets
  # @see #mount_table_for_hash
  #
  # @return [Hash] returns the tables that will be used to render on the template as a Hash
  def mount_tables_for_fieldsets
    hash = fetch_fieldsets
    hash.each do |key, value|
      html = mount_table_for_hash(value)
      hash[key] = html if html.present?
    end
    hash
  end

  # iterates over the template params and sets the fieldsets that will be will be displayed in tables
  # @see #set_fieldset_key
  #
  # @param [Hash] hash the hash that will contain the data will be displayed in tables
  #
  # @return [void]
  def build_template_params_hash(hash)
    @template_params.each_with_parent do |parent, key, value|
      next if value.blank? || key.blank?
      parent_name = set_fieldset_key(hash, parent, 'system_info')
      hash[parent_name][key] = value
    end
  end

  # builds the template params that wil be used to construct the fieldsets and sorts them alphabetically
  # @see #build_template_params_hash
  #
  # @param [Hash] hash the hash that will contain the template params that wil be used to construct the fieldsets sorted alphabetically
  #
  # @return [Hash] returns the hash that will contain the template params that wil be used to construct the fieldsets sorted alphabetically
  def fetch_fieldsets(hash = {})
    build_template_params_hash(hash)
    hash.keys.map(&:to_s).sort
    hash
  end

  # adds the fieldsets and the fieldsets_links to the template params
  # @see #fieldsets
  # @see #fieldsets_links
  #
  # @return [void]
  def setup_template_params_for_rendering
    @template_params[:fieldsets] = fieldsets
    @template_params[:fieldsets_links] = fieldsets_links
  end

  # renders the template or the default template with the template params
  # @see #execute_with_rescue
  # @see #setup_template_params_for_rendering
  #
  # @return [void]
  def render_template(template = nil)
    execute_with_rescue do
      current_template = template.present? ? template : @template_path
      setup_template_params_for_rendering
      Tilt.new(current_template).render(self, @template_params.stringify_keys)
    end
  end

  # Creates a archive from the render_template outpout and returns the filename and the path of the file
  # @see Tempfile#new
  # @see Tempfile#write
  # @see ObjectSpace#undefine_finalizer
  # @see Tempfile#close
  # @see #tempfile_details
  #
  # @return [Array<String>] returns an array containing the filename as first value, and the path to the tempfile created as second value
  def create_tempfile(output = render_template)
    tempfile = Tempfile.new([SecureRandom.uuid, ".#{@template_details[:template_extension]}"], encoding: 'utf-8')
    tempfile.write(output)
    ObjectSpace.undefine_finalizer(tempfile) # force garbage collector not to remove automatically the file
    tempfile.close
    tempfile_details(tempfile).slice(:filename, :path).values
  end

  # Executes the fetch_archives and returns the result or empty array in case of exception
  # @see #fetch_archives
  #
  # @return [Array] returns an array with file paths to the created archives
  def fetch_all_archives
    fetch_archives
  rescue
    []
  end

  # Creates the archive, compresses it , and then removes the temporary file and splits the archive if needed
  # @see #create_tempfile
  # @see #archive_files
  # @see #remove_tempfile
  # @see #split_archive
  #
  # @return [Array] returns an array with file paths to the created archives
  def fetch_archives(output = render_template)
    return [] if output.blank?
    filename, path = create_tempfile(output)
    archive = archive_files(File.dirname(path), filename, [expanded_path(path)])
    remove_tempfile(path)
    split_archive(archive, "part_#{filename}", 1024 * 1024 * 100) # 104_857_600
  end

  # If DEBUG_ASANA_TEMPLATE is present this method will only log the path , otherwise will remove the file.
  # @param [String] path The path of the Tempfile that needs to be removed or logged
  #
  # @return [void]
  def remove_tempfile(path)
    if ENV['DEBUG_ASANA_TEMPLATE']
      logger.debug(path)
    else
      FileUtils.rm_rf([path])
    end
  end
end

#optionsHash (readonly)

Returns Additional options sent by the middleware that will be used to provide additional informatio.

Returns:

  • (Hash)

    Additional options sent by the middleware that will be used to provide additional informatio



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 23

class ErrorPage
  include AsanaExceptionNotifier::ApplicationHelper

  attr_reader :template_path, :exception, :options, :template_details, :env, :request, :tempfile, :template_params

  # Initializes the instance with the template path that will be used to render the template,
  # the exception caught by the middleware and additional options sent by the middleware
  # @see #html_template
  # @see #setup_template_details
  # @see #parse_exception_options
  #
  # @param [String] template_path The template_path that will be used to render the exception details
  # @param [Exception] exception The exception that was caught by the middleware
  # @param [Hash] options Additional options that the middleware can send ( Default : {})
  #
  # @return [void]
  def initialize(template_path, exception, options)
    @exception = exception
    @options = options.symbolize_keys
    html_template(template_path)
    @template_details = setup_template_details
    @env = (@options[:env] || ENV.to_h).stringify_keys
    @request = action_dispatch? ? ActionDispatch::Request.new(@env) : Rack::Request.new(@env)
    @timestamp = Time.now
    parse_exception_options
  end

  # Initializes the instance with the template path that will be used to render the template,
  # the exception caught by the middleware and additional options sent by the middleware
  # @see #path_is_a_template
  # @see #expanded_path
  # @see #template_dir
  #
  # @param [String] path The template_path that will be used to render the exception details
  #
  # @return [void]
  def html_template(path)
    @template_path = if path_is_a_template?(path)
                       expanded_path(path)
                     else
                       File.join(template_dir, 'exception_details.html.erb')
                     end
  end

  # Returns true or false if ActionDispatch is available
  #
  # @return [Boolean] returns true if ActionDispatch::Request is defined, false otherwise
  def action_dispatch?
    defined?(ActionDispatch::Request)
  end

  # Gets the name and the extension of the template path, if was provided custom
  # ( this is needed in case someone wants something else than ERB template , since Tilt can support multiple formats)
  # @see #get_extension_and_name_from_file
  #
  # @return [Hash] Returns a hash containing the name and the extension of the template
  def setup_template_details
    template_extension = @template_path.scan(/\.(\w+)\.?(.*)?/)[0][0]
    get_extension_and_name_from_file(@template_path).merge(
      template_extension: template_extension
    )
  end

  # :reek:TooManyStatements: { max_statements: 10 }
  #
  # Fetches information about request, exception, environment and other additional information needed for the template
  # @see #fetch_basic_info
  # @see #exception_data
  # @see #setup_env_params
  # @see #filter_params
  # @see #session
  # @see #request_params
  # @see Rack::Request#cookies
  # @see ActionDispatch::Request#filtered_env
  # @see ActionDispatch::Request#filtered_parameters
  #
  # @return [Hash] Returns a hash containing all the information gathered about the exception, including env, cookies, session, and other additional information
  def parse_exception_options
    @template_params ||= {
      basic_info: fetch_basic_info,
      exception: @exception,
      request: @request,
      env: @request.respond_to?(:filtered_env) ? @request.filtered_env : @env,
      data: (@env.blank? ? {} : @env.fetch(:'exception_notifier.exception_data', {})).merge(@options[:data] || {}),
      exception_data: exception_data,
      request_data: setup_env_params,
      parameters: @request.respond_to?(:filtered_parameters) ? filter_params(@request.filtered_parameters) : filter_params(request_params),
      session: filter_params(session.respond_to?(:to_hash) ? session.to_hash : session.to_h),
      cookies: filter_params(@request.cookies.to_h)
    }.merge(@options).reject { |_key, value| value.blank? }
  end

  # returns the session from the request, (either from ActionDispatch or from Rack)
  #
  # @return [Hash] Returns the session of the request
  def session
    @request.session
  end

  # returns basic information about the system, like hostname, rails root directory, the process Id, the uname , the timestamp, and the Program name
  # @see Socket#gethostname
  # @see Rails::root
  # @see Sys::Uname#uname
  #
  # @return [Hash] Returns basic information about the system, like hostname, and other additionl information
  def fetch_basic_info
    {
      server:  Socket.gethostname,
      rails_root: defined?(Rails) ? Rails.root : nil,
      process: $PROCESS_ID,
      uname: Sys::Uname.uname,
      timestamp: @timestamp,
      pwd:  File.expand_path($PROGRAM_NAME)
    }
  end

  # returns information about the exception, like the class name, the message, the backtrace, the cause ( if gem 'cause' is used)
  #
  # @return [Hash] Returns information about the exception, like the class name, the message, the backtrace, the cause ( if gem 'cause' is used)
  def exception_data
    exception_service.merge(
      error_class: @exception.class.to_s,
      message:  @exception.respond_to?(:message) ? @exception.message : exception.inspect,
      backtrace: @exception.respond_to?(:backtrace) ? (@exception.backtrace || []).join("\n") : nil,
      cause: @exception.respond_to?(:cause) ? @exception.cause : nil
    )
  end

  # returns the instance variables defined by the exception, useful when using custom exceptions
  #
  # @return [Hash] Returns information about the instance variables defined by the exception, useful when using custom exceptions
  def exception_service
    hash = {}
    @exception.instance_variables.select do |ivar|
      attr_value = @exception.instance_variable_get(ivar)
      hash[ivar.to_s] = attr_value if attr_value.present?
    end
    hash
  end

  # returns information about URL, referer, http_method used, ip address and user agent
  #
  # @return [Hash] Returns information about URL, referer, http_method used, ip address and user agent
  def setup_env_params
    {
      url: @request.respond_to?(:original_url) ? @request.original_url : @request.path_info,
      referrer: @request.referer,
      http_method: action_dispatch? ? @request.method : @request.request_method,
      ip_address:  @request.respond_to?(:remote_ip) ? @request.remote_ip : @request.ip,
      user_agent: @request.user_agent
    }
  end

  # Filters sensitive information from parameters so that they won't get leaked into the template
  # @see AsanaExceptionNotifier::UnsafeFilter#new
  #
  # @return [Hash] Returns the information filtered , by using custom filters or the default one
  def filter_params(params)
    AsanaExceptionNotifier::UnsafeFilter.new(params, @options.fetch(:unsafe_options, [])).arguments
  end

  # returns the params sent with the initial request
  #
  # @return [Hash] Returns the params sent with the initial request
  def request_params
    @request.params
  rescue
    {}
  end

  # returns the names that will be used on the table header in the template
  # @see #fieldsets
  # @see #link_helper
  #
  # @return [String] returns the names that will be used on the table header in the template
  def fieldsets_links
    fieldsets.map { |key, _value| link_helper(key.to_s) }.join(' | ')
  end

  # returns fieldsets that will be showned in the template on separate table
  # @see #mount_tables_for_fieldsets
  #
  # @return [Array<Hash>] returns fieldsets that will be showned in the template on separate table
  def fieldsets
    @fieldsets ||= mount_tables_for_fieldsets
    @fieldsets
  end

  # returns fieldsets that will be showned in the template on separate table
  # @see #fetch_fieldsets
  # @see #mount_table_for_hash
  #
  # @return [Hash] returns the tables that will be used to render on the template as a Hash
  def mount_tables_for_fieldsets
    hash = fetch_fieldsets
    hash.each do |key, value|
      html = mount_table_for_hash(value)
      hash[key] = html if html.present?
    end
    hash
  end

  # iterates over the template params and sets the fieldsets that will be will be displayed in tables
  # @see #set_fieldset_key
  #
  # @param [Hash] hash the hash that will contain the data will be displayed in tables
  #
  # @return [void]
  def build_template_params_hash(hash)
    @template_params.each_with_parent do |parent, key, value|
      next if value.blank? || key.blank?
      parent_name = set_fieldset_key(hash, parent, 'system_info')
      hash[parent_name][key] = value
    end
  end

  # builds the template params that wil be used to construct the fieldsets and sorts them alphabetically
  # @see #build_template_params_hash
  #
  # @param [Hash] hash the hash that will contain the template params that wil be used to construct the fieldsets sorted alphabetically
  #
  # @return [Hash] returns the hash that will contain the template params that wil be used to construct the fieldsets sorted alphabetically
  def fetch_fieldsets(hash = {})
    build_template_params_hash(hash)
    hash.keys.map(&:to_s).sort
    hash
  end

  # adds the fieldsets and the fieldsets_links to the template params
  # @see #fieldsets
  # @see #fieldsets_links
  #
  # @return [void]
  def setup_template_params_for_rendering
    @template_params[:fieldsets] = fieldsets
    @template_params[:fieldsets_links] = fieldsets_links
  end

  # renders the template or the default template with the template params
  # @see #execute_with_rescue
  # @see #setup_template_params_for_rendering
  #
  # @return [void]
  def render_template(template = nil)
    execute_with_rescue do
      current_template = template.present? ? template : @template_path
      setup_template_params_for_rendering
      Tilt.new(current_template).render(self, @template_params.stringify_keys)
    end
  end

  # Creates a archive from the render_template outpout and returns the filename and the path of the file
  # @see Tempfile#new
  # @see Tempfile#write
  # @see ObjectSpace#undefine_finalizer
  # @see Tempfile#close
  # @see #tempfile_details
  #
  # @return [Array<String>] returns an array containing the filename as first value, and the path to the tempfile created as second value
  def create_tempfile(output = render_template)
    tempfile = Tempfile.new([SecureRandom.uuid, ".#{@template_details[:template_extension]}"], encoding: 'utf-8')
    tempfile.write(output)
    ObjectSpace.undefine_finalizer(tempfile) # force garbage collector not to remove automatically the file
    tempfile.close
    tempfile_details(tempfile).slice(:filename, :path).values
  end

  # Executes the fetch_archives and returns the result or empty array in case of exception
  # @see #fetch_archives
  #
  # @return [Array] returns an array with file paths to the created archives
  def fetch_all_archives
    fetch_archives
  rescue
    []
  end

  # Creates the archive, compresses it , and then removes the temporary file and splits the archive if needed
  # @see #create_tempfile
  # @see #archive_files
  # @see #remove_tempfile
  # @see #split_archive
  #
  # @return [Array] returns an array with file paths to the created archives
  def fetch_archives(output = render_template)
    return [] if output.blank?
    filename, path = create_tempfile(output)
    archive = archive_files(File.dirname(path), filename, [expanded_path(path)])
    remove_tempfile(path)
    split_archive(archive, "part_#{filename}", 1024 * 1024 * 100) # 104_857_600
  end

  # If DEBUG_ASANA_TEMPLATE is present this method will only log the path , otherwise will remove the file.
  # @param [String] path The path of the Tempfile that needs to be removed or logged
  #
  # @return [void]
  def remove_tempfile(path)
    if ENV['DEBUG_ASANA_TEMPLATE']
      logger.debug(path)
    else
      FileUtils.rm_rf([path])
    end
  end
end

#requestHash (readonly)

Returns The request that is built based on the environment, in order to provide more information.

Returns:

  • (Hash)

    The request that is built based on the environment, in order to provide more information



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 23

class ErrorPage
  include AsanaExceptionNotifier::ApplicationHelper

  attr_reader :template_path, :exception, :options, :template_details, :env, :request, :tempfile, :template_params

  # Initializes the instance with the template path that will be used to render the template,
  # the exception caught by the middleware and additional options sent by the middleware
  # @see #html_template
  # @see #setup_template_details
  # @see #parse_exception_options
  #
  # @param [String] template_path The template_path that will be used to render the exception details
  # @param [Exception] exception The exception that was caught by the middleware
  # @param [Hash] options Additional options that the middleware can send ( Default : {})
  #
  # @return [void]
  def initialize(template_path, exception, options)
    @exception = exception
    @options = options.symbolize_keys
    html_template(template_path)
    @template_details = setup_template_details
    @env = (@options[:env] || ENV.to_h).stringify_keys
    @request = action_dispatch? ? ActionDispatch::Request.new(@env) : Rack::Request.new(@env)
    @timestamp = Time.now
    parse_exception_options
  end

  # Initializes the instance with the template path that will be used to render the template,
  # the exception caught by the middleware and additional options sent by the middleware
  # @see #path_is_a_template
  # @see #expanded_path
  # @see #template_dir
  #
  # @param [String] path The template_path that will be used to render the exception details
  #
  # @return [void]
  def html_template(path)
    @template_path = if path_is_a_template?(path)
                       expanded_path(path)
                     else
                       File.join(template_dir, 'exception_details.html.erb')
                     end
  end

  # Returns true or false if ActionDispatch is available
  #
  # @return [Boolean] returns true if ActionDispatch::Request is defined, false otherwise
  def action_dispatch?
    defined?(ActionDispatch::Request)
  end

  # Gets the name and the extension of the template path, if was provided custom
  # ( this is needed in case someone wants something else than ERB template , since Tilt can support multiple formats)
  # @see #get_extension_and_name_from_file
  #
  # @return [Hash] Returns a hash containing the name and the extension of the template
  def setup_template_details
    template_extension = @template_path.scan(/\.(\w+)\.?(.*)?/)[0][0]
    get_extension_and_name_from_file(@template_path).merge(
      template_extension: template_extension
    )
  end

  # :reek:TooManyStatements: { max_statements: 10 }
  #
  # Fetches information about request, exception, environment and other additional information needed for the template
  # @see #fetch_basic_info
  # @see #exception_data
  # @see #setup_env_params
  # @see #filter_params
  # @see #session
  # @see #request_params
  # @see Rack::Request#cookies
  # @see ActionDispatch::Request#filtered_env
  # @see ActionDispatch::Request#filtered_parameters
  #
  # @return [Hash] Returns a hash containing all the information gathered about the exception, including env, cookies, session, and other additional information
  def parse_exception_options
    @template_params ||= {
      basic_info: fetch_basic_info,
      exception: @exception,
      request: @request,
      env: @request.respond_to?(:filtered_env) ? @request.filtered_env : @env,
      data: (@env.blank? ? {} : @env.fetch(:'exception_notifier.exception_data', {})).merge(@options[:data] || {}),
      exception_data: exception_data,
      request_data: setup_env_params,
      parameters: @request.respond_to?(:filtered_parameters) ? filter_params(@request.filtered_parameters) : filter_params(request_params),
      session: filter_params(session.respond_to?(:to_hash) ? session.to_hash : session.to_h),
      cookies: filter_params(@request.cookies.to_h)
    }.merge(@options).reject { |_key, value| value.blank? }
  end

  # returns the session from the request, (either from ActionDispatch or from Rack)
  #
  # @return [Hash] Returns the session of the request
  def session
    @request.session
  end

  # returns basic information about the system, like hostname, rails root directory, the process Id, the uname , the timestamp, and the Program name
  # @see Socket#gethostname
  # @see Rails::root
  # @see Sys::Uname#uname
  #
  # @return [Hash] Returns basic information about the system, like hostname, and other additionl information
  def fetch_basic_info
    {
      server:  Socket.gethostname,
      rails_root: defined?(Rails) ? Rails.root : nil,
      process: $PROCESS_ID,
      uname: Sys::Uname.uname,
      timestamp: @timestamp,
      pwd:  File.expand_path($PROGRAM_NAME)
    }
  end

  # returns information about the exception, like the class name, the message, the backtrace, the cause ( if gem 'cause' is used)
  #
  # @return [Hash] Returns information about the exception, like the class name, the message, the backtrace, the cause ( if gem 'cause' is used)
  def exception_data
    exception_service.merge(
      error_class: @exception.class.to_s,
      message:  @exception.respond_to?(:message) ? @exception.message : exception.inspect,
      backtrace: @exception.respond_to?(:backtrace) ? (@exception.backtrace || []).join("\n") : nil,
      cause: @exception.respond_to?(:cause) ? @exception.cause : nil
    )
  end

  # returns the instance variables defined by the exception, useful when using custom exceptions
  #
  # @return [Hash] Returns information about the instance variables defined by the exception, useful when using custom exceptions
  def exception_service
    hash = {}
    @exception.instance_variables.select do |ivar|
      attr_value = @exception.instance_variable_get(ivar)
      hash[ivar.to_s] = attr_value if attr_value.present?
    end
    hash
  end

  # returns information about URL, referer, http_method used, ip address and user agent
  #
  # @return [Hash] Returns information about URL, referer, http_method used, ip address and user agent
  def setup_env_params
    {
      url: @request.respond_to?(:original_url) ? @request.original_url : @request.path_info,
      referrer: @request.referer,
      http_method: action_dispatch? ? @request.method : @request.request_method,
      ip_address:  @request.respond_to?(:remote_ip) ? @request.remote_ip : @request.ip,
      user_agent: @request.user_agent
    }
  end

  # Filters sensitive information from parameters so that they won't get leaked into the template
  # @see AsanaExceptionNotifier::UnsafeFilter#new
  #
  # @return [Hash] Returns the information filtered , by using custom filters or the default one
  def filter_params(params)
    AsanaExceptionNotifier::UnsafeFilter.new(params, @options.fetch(:unsafe_options, [])).arguments
  end

  # returns the params sent with the initial request
  #
  # @return [Hash] Returns the params sent with the initial request
  def request_params
    @request.params
  rescue
    {}
  end

  # returns the names that will be used on the table header in the template
  # @see #fieldsets
  # @see #link_helper
  #
  # @return [String] returns the names that will be used on the table header in the template
  def fieldsets_links
    fieldsets.map { |key, _value| link_helper(key.to_s) }.join(' | ')
  end

  # returns fieldsets that will be showned in the template on separate table
  # @see #mount_tables_for_fieldsets
  #
  # @return [Array<Hash>] returns fieldsets that will be showned in the template on separate table
  def fieldsets
    @fieldsets ||= mount_tables_for_fieldsets
    @fieldsets
  end

  # returns fieldsets that will be showned in the template on separate table
  # @see #fetch_fieldsets
  # @see #mount_table_for_hash
  #
  # @return [Hash] returns the tables that will be used to render on the template as a Hash
  def mount_tables_for_fieldsets
    hash = fetch_fieldsets
    hash.each do |key, value|
      html = mount_table_for_hash(value)
      hash[key] = html if html.present?
    end
    hash
  end

  # iterates over the template params and sets the fieldsets that will be will be displayed in tables
  # @see #set_fieldset_key
  #
  # @param [Hash] hash the hash that will contain the data will be displayed in tables
  #
  # @return [void]
  def build_template_params_hash(hash)
    @template_params.each_with_parent do |parent, key, value|
      next if value.blank? || key.blank?
      parent_name = set_fieldset_key(hash, parent, 'system_info')
      hash[parent_name][key] = value
    end
  end

  # builds the template params that wil be used to construct the fieldsets and sorts them alphabetically
  # @see #build_template_params_hash
  #
  # @param [Hash] hash the hash that will contain the template params that wil be used to construct the fieldsets sorted alphabetically
  #
  # @return [Hash] returns the hash that will contain the template params that wil be used to construct the fieldsets sorted alphabetically
  def fetch_fieldsets(hash = {})
    build_template_params_hash(hash)
    hash.keys.map(&:to_s).sort
    hash
  end

  # adds the fieldsets and the fieldsets_links to the template params
  # @see #fieldsets
  # @see #fieldsets_links
  #
  # @return [void]
  def setup_template_params_for_rendering
    @template_params[:fieldsets] = fieldsets
    @template_params[:fieldsets_links] = fieldsets_links
  end

  # renders the template or the default template with the template params
  # @see #execute_with_rescue
  # @see #setup_template_params_for_rendering
  #
  # @return [void]
  def render_template(template = nil)
    execute_with_rescue do
      current_template = template.present? ? template : @template_path
      setup_template_params_for_rendering
      Tilt.new(current_template).render(self, @template_params.stringify_keys)
    end
  end

  # Creates a archive from the render_template outpout and returns the filename and the path of the file
  # @see Tempfile#new
  # @see Tempfile#write
  # @see ObjectSpace#undefine_finalizer
  # @see Tempfile#close
  # @see #tempfile_details
  #
  # @return [Array<String>] returns an array containing the filename as first value, and the path to the tempfile created as second value
  def create_tempfile(output = render_template)
    tempfile = Tempfile.new([SecureRandom.uuid, ".#{@template_details[:template_extension]}"], encoding: 'utf-8')
    tempfile.write(output)
    ObjectSpace.undefine_finalizer(tempfile) # force garbage collector not to remove automatically the file
    tempfile.close
    tempfile_details(tempfile).slice(:filename, :path).values
  end

  # Executes the fetch_archives and returns the result or empty array in case of exception
  # @see #fetch_archives
  #
  # @return [Array] returns an array with file paths to the created archives
  def fetch_all_archives
    fetch_archives
  rescue
    []
  end

  # Creates the archive, compresses it , and then removes the temporary file and splits the archive if needed
  # @see #create_tempfile
  # @see #archive_files
  # @see #remove_tempfile
  # @see #split_archive
  #
  # @return [Array] returns an array with file paths to the created archives
  def fetch_archives(output = render_template)
    return [] if output.blank?
    filename, path = create_tempfile(output)
    archive = archive_files(File.dirname(path), filename, [expanded_path(path)])
    remove_tempfile(path)
    split_archive(archive, "part_#{filename}", 1024 * 1024 * 100) # 104_857_600
  end

  # If DEBUG_ASANA_TEMPLATE is present this method will only log the path , otherwise will remove the file.
  # @param [String] path The path of the Tempfile that needs to be removed or logged
  #
  # @return [void]
  def remove_tempfile(path)
    if ENV['DEBUG_ASANA_TEMPLATE']
      logger.debug(path)
    else
      FileUtils.rm_rf([path])
    end
  end
end

#tempfileHash (readonly)

Returns The archive that will be created and then splitted into multiple archives (if needed ).

Returns:

  • (Hash)

    The archive that will be created and then splitted into multiple archives (if needed )



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 23

class ErrorPage
  include AsanaExceptionNotifier::ApplicationHelper

  attr_reader :template_path, :exception, :options, :template_details, :env, :request, :tempfile, :template_params

  # Initializes the instance with the template path that will be used to render the template,
  # the exception caught by the middleware and additional options sent by the middleware
  # @see #html_template
  # @see #setup_template_details
  # @see #parse_exception_options
  #
  # @param [String] template_path The template_path that will be used to render the exception details
  # @param [Exception] exception The exception that was caught by the middleware
  # @param [Hash] options Additional options that the middleware can send ( Default : {})
  #
  # @return [void]
  def initialize(template_path, exception, options)
    @exception = exception
    @options = options.symbolize_keys
    html_template(template_path)
    @template_details = setup_template_details
    @env = (@options[:env] || ENV.to_h).stringify_keys
    @request = action_dispatch? ? ActionDispatch::Request.new(@env) : Rack::Request.new(@env)
    @timestamp = Time.now
    parse_exception_options
  end

  # Initializes the instance with the template path that will be used to render the template,
  # the exception caught by the middleware and additional options sent by the middleware
  # @see #path_is_a_template
  # @see #expanded_path
  # @see #template_dir
  #
  # @param [String] path The template_path that will be used to render the exception details
  #
  # @return [void]
  def html_template(path)
    @template_path = if path_is_a_template?(path)
                       expanded_path(path)
                     else
                       File.join(template_dir, 'exception_details.html.erb')
                     end
  end

  # Returns true or false if ActionDispatch is available
  #
  # @return [Boolean] returns true if ActionDispatch::Request is defined, false otherwise
  def action_dispatch?
    defined?(ActionDispatch::Request)
  end

  # Gets the name and the extension of the template path, if was provided custom
  # ( this is needed in case someone wants something else than ERB template , since Tilt can support multiple formats)
  # @see #get_extension_and_name_from_file
  #
  # @return [Hash] Returns a hash containing the name and the extension of the template
  def setup_template_details
    template_extension = @template_path.scan(/\.(\w+)\.?(.*)?/)[0][0]
    get_extension_and_name_from_file(@template_path).merge(
      template_extension: template_extension
    )
  end

  # :reek:TooManyStatements: { max_statements: 10 }
  #
  # Fetches information about request, exception, environment and other additional information needed for the template
  # @see #fetch_basic_info
  # @see #exception_data
  # @see #setup_env_params
  # @see #filter_params
  # @see #session
  # @see #request_params
  # @see Rack::Request#cookies
  # @see ActionDispatch::Request#filtered_env
  # @see ActionDispatch::Request#filtered_parameters
  #
  # @return [Hash] Returns a hash containing all the information gathered about the exception, including env, cookies, session, and other additional information
  def parse_exception_options
    @template_params ||= {
      basic_info: fetch_basic_info,
      exception: @exception,
      request: @request,
      env: @request.respond_to?(:filtered_env) ? @request.filtered_env : @env,
      data: (@env.blank? ? {} : @env.fetch(:'exception_notifier.exception_data', {})).merge(@options[:data] || {}),
      exception_data: exception_data,
      request_data: setup_env_params,
      parameters: @request.respond_to?(:filtered_parameters) ? filter_params(@request.filtered_parameters) : filter_params(request_params),
      session: filter_params(session.respond_to?(:to_hash) ? session.to_hash : session.to_h),
      cookies: filter_params(@request.cookies.to_h)
    }.merge(@options).reject { |_key, value| value.blank? }
  end

  # returns the session from the request, (either from ActionDispatch or from Rack)
  #
  # @return [Hash] Returns the session of the request
  def session
    @request.session
  end

  # returns basic information about the system, like hostname, rails root directory, the process Id, the uname , the timestamp, and the Program name
  # @see Socket#gethostname
  # @see Rails::root
  # @see Sys::Uname#uname
  #
  # @return [Hash] Returns basic information about the system, like hostname, and other additionl information
  def fetch_basic_info
    {
      server:  Socket.gethostname,
      rails_root: defined?(Rails) ? Rails.root : nil,
      process: $PROCESS_ID,
      uname: Sys::Uname.uname,
      timestamp: @timestamp,
      pwd:  File.expand_path($PROGRAM_NAME)
    }
  end

  # returns information about the exception, like the class name, the message, the backtrace, the cause ( if gem 'cause' is used)
  #
  # @return [Hash] Returns information about the exception, like the class name, the message, the backtrace, the cause ( if gem 'cause' is used)
  def exception_data
    exception_service.merge(
      error_class: @exception.class.to_s,
      message:  @exception.respond_to?(:message) ? @exception.message : exception.inspect,
      backtrace: @exception.respond_to?(:backtrace) ? (@exception.backtrace || []).join("\n") : nil,
      cause: @exception.respond_to?(:cause) ? @exception.cause : nil
    )
  end

  # returns the instance variables defined by the exception, useful when using custom exceptions
  #
  # @return [Hash] Returns information about the instance variables defined by the exception, useful when using custom exceptions
  def exception_service
    hash = {}
    @exception.instance_variables.select do |ivar|
      attr_value = @exception.instance_variable_get(ivar)
      hash[ivar.to_s] = attr_value if attr_value.present?
    end
    hash
  end

  # returns information about URL, referer, http_method used, ip address and user agent
  #
  # @return [Hash] Returns information about URL, referer, http_method used, ip address and user agent
  def setup_env_params
    {
      url: @request.respond_to?(:original_url) ? @request.original_url : @request.path_info,
      referrer: @request.referer,
      http_method: action_dispatch? ? @request.method : @request.request_method,
      ip_address:  @request.respond_to?(:remote_ip) ? @request.remote_ip : @request.ip,
      user_agent: @request.user_agent
    }
  end

  # Filters sensitive information from parameters so that they won't get leaked into the template
  # @see AsanaExceptionNotifier::UnsafeFilter#new
  #
  # @return [Hash] Returns the information filtered , by using custom filters or the default one
  def filter_params(params)
    AsanaExceptionNotifier::UnsafeFilter.new(params, @options.fetch(:unsafe_options, [])).arguments
  end

  # returns the params sent with the initial request
  #
  # @return [Hash] Returns the params sent with the initial request
  def request_params
    @request.params
  rescue
    {}
  end

  # returns the names that will be used on the table header in the template
  # @see #fieldsets
  # @see #link_helper
  #
  # @return [String] returns the names that will be used on the table header in the template
  def fieldsets_links
    fieldsets.map { |key, _value| link_helper(key.to_s) }.join(' | ')
  end

  # returns fieldsets that will be showned in the template on separate table
  # @see #mount_tables_for_fieldsets
  #
  # @return [Array<Hash>] returns fieldsets that will be showned in the template on separate table
  def fieldsets
    @fieldsets ||= mount_tables_for_fieldsets
    @fieldsets
  end

  # returns fieldsets that will be showned in the template on separate table
  # @see #fetch_fieldsets
  # @see #mount_table_for_hash
  #
  # @return [Hash] returns the tables that will be used to render on the template as a Hash
  def mount_tables_for_fieldsets
    hash = fetch_fieldsets
    hash.each do |key, value|
      html = mount_table_for_hash(value)
      hash[key] = html if html.present?
    end
    hash
  end

  # iterates over the template params and sets the fieldsets that will be will be displayed in tables
  # @see #set_fieldset_key
  #
  # @param [Hash] hash the hash that will contain the data will be displayed in tables
  #
  # @return [void]
  def build_template_params_hash(hash)
    @template_params.each_with_parent do |parent, key, value|
      next if value.blank? || key.blank?
      parent_name = set_fieldset_key(hash, parent, 'system_info')
      hash[parent_name][key] = value
    end
  end

  # builds the template params that wil be used to construct the fieldsets and sorts them alphabetically
  # @see #build_template_params_hash
  #
  # @param [Hash] hash the hash that will contain the template params that wil be used to construct the fieldsets sorted alphabetically
  #
  # @return [Hash] returns the hash that will contain the template params that wil be used to construct the fieldsets sorted alphabetically
  def fetch_fieldsets(hash = {})
    build_template_params_hash(hash)
    hash.keys.map(&:to_s).sort
    hash
  end

  # adds the fieldsets and the fieldsets_links to the template params
  # @see #fieldsets
  # @see #fieldsets_links
  #
  # @return [void]
  def setup_template_params_for_rendering
    @template_params[:fieldsets] = fieldsets
    @template_params[:fieldsets_links] = fieldsets_links
  end

  # renders the template or the default template with the template params
  # @see #execute_with_rescue
  # @see #setup_template_params_for_rendering
  #
  # @return [void]
  def render_template(template = nil)
    execute_with_rescue do
      current_template = template.present? ? template : @template_path
      setup_template_params_for_rendering
      Tilt.new(current_template).render(self, @template_params.stringify_keys)
    end
  end

  # Creates a archive from the render_template outpout and returns the filename and the path of the file
  # @see Tempfile#new
  # @see Tempfile#write
  # @see ObjectSpace#undefine_finalizer
  # @see Tempfile#close
  # @see #tempfile_details
  #
  # @return [Array<String>] returns an array containing the filename as first value, and the path to the tempfile created as second value
  def create_tempfile(output = render_template)
    tempfile = Tempfile.new([SecureRandom.uuid, ".#{@template_details[:template_extension]}"], encoding: 'utf-8')
    tempfile.write(output)
    ObjectSpace.undefine_finalizer(tempfile) # force garbage collector not to remove automatically the file
    tempfile.close
    tempfile_details(tempfile).slice(:filename, :path).values
  end

  # Executes the fetch_archives and returns the result or empty array in case of exception
  # @see #fetch_archives
  #
  # @return [Array] returns an array with file paths to the created archives
  def fetch_all_archives
    fetch_archives
  rescue
    []
  end

  # Creates the archive, compresses it , and then removes the temporary file and splits the archive if needed
  # @see #create_tempfile
  # @see #archive_files
  # @see #remove_tempfile
  # @see #split_archive
  #
  # @return [Array] returns an array with file paths to the created archives
  def fetch_archives(output = render_template)
    return [] if output.blank?
    filename, path = create_tempfile(output)
    archive = archive_files(File.dirname(path), filename, [expanded_path(path)])
    remove_tempfile(path)
    split_archive(archive, "part_#{filename}", 1024 * 1024 * 100) # 104_857_600
  end

  # If DEBUG_ASANA_TEMPLATE is present this method will only log the path , otherwise will remove the file.
  # @param [String] path The path of the Tempfile that needs to be removed or logged
  #
  # @return [void]
  def remove_tempfile(path)
    if ENV['DEBUG_ASANA_TEMPLATE']
      logger.debug(path)
    else
      FileUtils.rm_rf([path])
    end
  end
end

#template_detailsHash (readonly)

Returns The name and the extension of the template.

Returns:

  • (Hash)

    The name and the extension of the template



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 23

class ErrorPage
  include AsanaExceptionNotifier::ApplicationHelper

  attr_reader :template_path, :exception, :options, :template_details, :env, :request, :tempfile, :template_params

  # Initializes the instance with the template path that will be used to render the template,
  # the exception caught by the middleware and additional options sent by the middleware
  # @see #html_template
  # @see #setup_template_details
  # @see #parse_exception_options
  #
  # @param [String] template_path The template_path that will be used to render the exception details
  # @param [Exception] exception The exception that was caught by the middleware
  # @param [Hash] options Additional options that the middleware can send ( Default : {})
  #
  # @return [void]
  def initialize(template_path, exception, options)
    @exception = exception
    @options = options.symbolize_keys
    html_template(template_path)
    @template_details = setup_template_details
    @env = (@options[:env] || ENV.to_h).stringify_keys
    @request = action_dispatch? ? ActionDispatch::Request.new(@env) : Rack::Request.new(@env)
    @timestamp = Time.now
    parse_exception_options
  end

  # Initializes the instance with the template path that will be used to render the template,
  # the exception caught by the middleware and additional options sent by the middleware
  # @see #path_is_a_template
  # @see #expanded_path
  # @see #template_dir
  #
  # @param [String] path The template_path that will be used to render the exception details
  #
  # @return [void]
  def html_template(path)
    @template_path = if path_is_a_template?(path)
                       expanded_path(path)
                     else
                       File.join(template_dir, 'exception_details.html.erb')
                     end
  end

  # Returns true or false if ActionDispatch is available
  #
  # @return [Boolean] returns true if ActionDispatch::Request is defined, false otherwise
  def action_dispatch?
    defined?(ActionDispatch::Request)
  end

  # Gets the name and the extension of the template path, if was provided custom
  # ( this is needed in case someone wants something else than ERB template , since Tilt can support multiple formats)
  # @see #get_extension_and_name_from_file
  #
  # @return [Hash] Returns a hash containing the name and the extension of the template
  def setup_template_details
    template_extension = @template_path.scan(/\.(\w+)\.?(.*)?/)[0][0]
    get_extension_and_name_from_file(@template_path).merge(
      template_extension: template_extension
    )
  end

  # :reek:TooManyStatements: { max_statements: 10 }
  #
  # Fetches information about request, exception, environment and other additional information needed for the template
  # @see #fetch_basic_info
  # @see #exception_data
  # @see #setup_env_params
  # @see #filter_params
  # @see #session
  # @see #request_params
  # @see Rack::Request#cookies
  # @see ActionDispatch::Request#filtered_env
  # @see ActionDispatch::Request#filtered_parameters
  #
  # @return [Hash] Returns a hash containing all the information gathered about the exception, including env, cookies, session, and other additional information
  def parse_exception_options
    @template_params ||= {
      basic_info: fetch_basic_info,
      exception: @exception,
      request: @request,
      env: @request.respond_to?(:filtered_env) ? @request.filtered_env : @env,
      data: (@env.blank? ? {} : @env.fetch(:'exception_notifier.exception_data', {})).merge(@options[:data] || {}),
      exception_data: exception_data,
      request_data: setup_env_params,
      parameters: @request.respond_to?(:filtered_parameters) ? filter_params(@request.filtered_parameters) : filter_params(request_params),
      session: filter_params(session.respond_to?(:to_hash) ? session.to_hash : session.to_h),
      cookies: filter_params(@request.cookies.to_h)
    }.merge(@options).reject { |_key, value| value.blank? }
  end

  # returns the session from the request, (either from ActionDispatch or from Rack)
  #
  # @return [Hash] Returns the session of the request
  def session
    @request.session
  end

  # returns basic information about the system, like hostname, rails root directory, the process Id, the uname , the timestamp, and the Program name
  # @see Socket#gethostname
  # @see Rails::root
  # @see Sys::Uname#uname
  #
  # @return [Hash] Returns basic information about the system, like hostname, and other additionl information
  def fetch_basic_info
    {
      server:  Socket.gethostname,
      rails_root: defined?(Rails) ? Rails.root : nil,
      process: $PROCESS_ID,
      uname: Sys::Uname.uname,
      timestamp: @timestamp,
      pwd:  File.expand_path($PROGRAM_NAME)
    }
  end

  # returns information about the exception, like the class name, the message, the backtrace, the cause ( if gem 'cause' is used)
  #
  # @return [Hash] Returns information about the exception, like the class name, the message, the backtrace, the cause ( if gem 'cause' is used)
  def exception_data
    exception_service.merge(
      error_class: @exception.class.to_s,
      message:  @exception.respond_to?(:message) ? @exception.message : exception.inspect,
      backtrace: @exception.respond_to?(:backtrace) ? (@exception.backtrace || []).join("\n") : nil,
      cause: @exception.respond_to?(:cause) ? @exception.cause : nil
    )
  end

  # returns the instance variables defined by the exception, useful when using custom exceptions
  #
  # @return [Hash] Returns information about the instance variables defined by the exception, useful when using custom exceptions
  def exception_service
    hash = {}
    @exception.instance_variables.select do |ivar|
      attr_value = @exception.instance_variable_get(ivar)
      hash[ivar.to_s] = attr_value if attr_value.present?
    end
    hash
  end

  # returns information about URL, referer, http_method used, ip address and user agent
  #
  # @return [Hash] Returns information about URL, referer, http_method used, ip address and user agent
  def setup_env_params
    {
      url: @request.respond_to?(:original_url) ? @request.original_url : @request.path_info,
      referrer: @request.referer,
      http_method: action_dispatch? ? @request.method : @request.request_method,
      ip_address:  @request.respond_to?(:remote_ip) ? @request.remote_ip : @request.ip,
      user_agent: @request.user_agent
    }
  end

  # Filters sensitive information from parameters so that they won't get leaked into the template
  # @see AsanaExceptionNotifier::UnsafeFilter#new
  #
  # @return [Hash] Returns the information filtered , by using custom filters or the default one
  def filter_params(params)
    AsanaExceptionNotifier::UnsafeFilter.new(params, @options.fetch(:unsafe_options, [])).arguments
  end

  # returns the params sent with the initial request
  #
  # @return [Hash] Returns the params sent with the initial request
  def request_params
    @request.params
  rescue
    {}
  end

  # returns the names that will be used on the table header in the template
  # @see #fieldsets
  # @see #link_helper
  #
  # @return [String] returns the names that will be used on the table header in the template
  def fieldsets_links
    fieldsets.map { |key, _value| link_helper(key.to_s) }.join(' | ')
  end

  # returns fieldsets that will be showned in the template on separate table
  # @see #mount_tables_for_fieldsets
  #
  # @return [Array<Hash>] returns fieldsets that will be showned in the template on separate table
  def fieldsets
    @fieldsets ||= mount_tables_for_fieldsets
    @fieldsets
  end

  # returns fieldsets that will be showned in the template on separate table
  # @see #fetch_fieldsets
  # @see #mount_table_for_hash
  #
  # @return [Hash] returns the tables that will be used to render on the template as a Hash
  def mount_tables_for_fieldsets
    hash = fetch_fieldsets
    hash.each do |key, value|
      html = mount_table_for_hash(value)
      hash[key] = html if html.present?
    end
    hash
  end

  # iterates over the template params and sets the fieldsets that will be will be displayed in tables
  # @see #set_fieldset_key
  #
  # @param [Hash] hash the hash that will contain the data will be displayed in tables
  #
  # @return [void]
  def build_template_params_hash(hash)
    @template_params.each_with_parent do |parent, key, value|
      next if value.blank? || key.blank?
      parent_name = set_fieldset_key(hash, parent, 'system_info')
      hash[parent_name][key] = value
    end
  end

  # builds the template params that wil be used to construct the fieldsets and sorts them alphabetically
  # @see #build_template_params_hash
  #
  # @param [Hash] hash the hash that will contain the template params that wil be used to construct the fieldsets sorted alphabetically
  #
  # @return [Hash] returns the hash that will contain the template params that wil be used to construct the fieldsets sorted alphabetically
  def fetch_fieldsets(hash = {})
    build_template_params_hash(hash)
    hash.keys.map(&:to_s).sort
    hash
  end

  # adds the fieldsets and the fieldsets_links to the template params
  # @see #fieldsets
  # @see #fieldsets_links
  #
  # @return [void]
  def setup_template_params_for_rendering
    @template_params[:fieldsets] = fieldsets
    @template_params[:fieldsets_links] = fieldsets_links
  end

  # renders the template or the default template with the template params
  # @see #execute_with_rescue
  # @see #setup_template_params_for_rendering
  #
  # @return [void]
  def render_template(template = nil)
    execute_with_rescue do
      current_template = template.present? ? template : @template_path
      setup_template_params_for_rendering
      Tilt.new(current_template).render(self, @template_params.stringify_keys)
    end
  end

  # Creates a archive from the render_template outpout and returns the filename and the path of the file
  # @see Tempfile#new
  # @see Tempfile#write
  # @see ObjectSpace#undefine_finalizer
  # @see Tempfile#close
  # @see #tempfile_details
  #
  # @return [Array<String>] returns an array containing the filename as first value, and the path to the tempfile created as second value
  def create_tempfile(output = render_template)
    tempfile = Tempfile.new([SecureRandom.uuid, ".#{@template_details[:template_extension]}"], encoding: 'utf-8')
    tempfile.write(output)
    ObjectSpace.undefine_finalizer(tempfile) # force garbage collector not to remove automatically the file
    tempfile.close
    tempfile_details(tempfile).slice(:filename, :path).values
  end

  # Executes the fetch_archives and returns the result or empty array in case of exception
  # @see #fetch_archives
  #
  # @return [Array] returns an array with file paths to the created archives
  def fetch_all_archives
    fetch_archives
  rescue
    []
  end

  # Creates the archive, compresses it , and then removes the temporary file and splits the archive if needed
  # @see #create_tempfile
  # @see #archive_files
  # @see #remove_tempfile
  # @see #split_archive
  #
  # @return [Array] returns an array with file paths to the created archives
  def fetch_archives(output = render_template)
    return [] if output.blank?
    filename, path = create_tempfile(output)
    archive = archive_files(File.dirname(path), filename, [expanded_path(path)])
    remove_tempfile(path)
    split_archive(archive, "part_#{filename}", 1024 * 1024 * 100) # 104_857_600
  end

  # If DEBUG_ASANA_TEMPLATE is present this method will only log the path , otherwise will remove the file.
  # @param [String] path The path of the Tempfile that needs to be removed or logged
  #
  # @return [void]
  def remove_tempfile(path)
    if ENV['DEBUG_ASANA_TEMPLATE']
      logger.debug(path)
    else
      FileUtils.rm_rf([path])
    end
  end
end

#template_paramsHash (readonly)

Returns The template params that will be sent to the template.

Returns:

  • (Hash)

    The template params that will be sent to the template



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 23

class ErrorPage
  include AsanaExceptionNotifier::ApplicationHelper

  attr_reader :template_path, :exception, :options, :template_details, :env, :request, :tempfile, :template_params

  # Initializes the instance with the template path that will be used to render the template,
  # the exception caught by the middleware and additional options sent by the middleware
  # @see #html_template
  # @see #setup_template_details
  # @see #parse_exception_options
  #
  # @param [String] template_path The template_path that will be used to render the exception details
  # @param [Exception] exception The exception that was caught by the middleware
  # @param [Hash] options Additional options that the middleware can send ( Default : {})
  #
  # @return [void]
  def initialize(template_path, exception, options)
    @exception = exception
    @options = options.symbolize_keys
    html_template(template_path)
    @template_details = setup_template_details
    @env = (@options[:env] || ENV.to_h).stringify_keys
    @request = action_dispatch? ? ActionDispatch::Request.new(@env) : Rack::Request.new(@env)
    @timestamp = Time.now
    parse_exception_options
  end

  # Initializes the instance with the template path that will be used to render the template,
  # the exception caught by the middleware and additional options sent by the middleware
  # @see #path_is_a_template
  # @see #expanded_path
  # @see #template_dir
  #
  # @param [String] path The template_path that will be used to render the exception details
  #
  # @return [void]
  def html_template(path)
    @template_path = if path_is_a_template?(path)
                       expanded_path(path)
                     else
                       File.join(template_dir, 'exception_details.html.erb')
                     end
  end

  # Returns true or false if ActionDispatch is available
  #
  # @return [Boolean] returns true if ActionDispatch::Request is defined, false otherwise
  def action_dispatch?
    defined?(ActionDispatch::Request)
  end

  # Gets the name and the extension of the template path, if was provided custom
  # ( this is needed in case someone wants something else than ERB template , since Tilt can support multiple formats)
  # @see #get_extension_and_name_from_file
  #
  # @return [Hash] Returns a hash containing the name and the extension of the template
  def setup_template_details
    template_extension = @template_path.scan(/\.(\w+)\.?(.*)?/)[0][0]
    get_extension_and_name_from_file(@template_path).merge(
      template_extension: template_extension
    )
  end

  # :reek:TooManyStatements: { max_statements: 10 }
  #
  # Fetches information about request, exception, environment and other additional information needed for the template
  # @see #fetch_basic_info
  # @see #exception_data
  # @see #setup_env_params
  # @see #filter_params
  # @see #session
  # @see #request_params
  # @see Rack::Request#cookies
  # @see ActionDispatch::Request#filtered_env
  # @see ActionDispatch::Request#filtered_parameters
  #
  # @return [Hash] Returns a hash containing all the information gathered about the exception, including env, cookies, session, and other additional information
  def parse_exception_options
    @template_params ||= {
      basic_info: fetch_basic_info,
      exception: @exception,
      request: @request,
      env: @request.respond_to?(:filtered_env) ? @request.filtered_env : @env,
      data: (@env.blank? ? {} : @env.fetch(:'exception_notifier.exception_data', {})).merge(@options[:data] || {}),
      exception_data: exception_data,
      request_data: setup_env_params,
      parameters: @request.respond_to?(:filtered_parameters) ? filter_params(@request.filtered_parameters) : filter_params(request_params),
      session: filter_params(session.respond_to?(:to_hash) ? session.to_hash : session.to_h),
      cookies: filter_params(@request.cookies.to_h)
    }.merge(@options).reject { |_key, value| value.blank? }
  end

  # returns the session from the request, (either from ActionDispatch or from Rack)
  #
  # @return [Hash] Returns the session of the request
  def session
    @request.session
  end

  # returns basic information about the system, like hostname, rails root directory, the process Id, the uname , the timestamp, and the Program name
  # @see Socket#gethostname
  # @see Rails::root
  # @see Sys::Uname#uname
  #
  # @return [Hash] Returns basic information about the system, like hostname, and other additionl information
  def fetch_basic_info
    {
      server:  Socket.gethostname,
      rails_root: defined?(Rails) ? Rails.root : nil,
      process: $PROCESS_ID,
      uname: Sys::Uname.uname,
      timestamp: @timestamp,
      pwd:  File.expand_path($PROGRAM_NAME)
    }
  end

  # returns information about the exception, like the class name, the message, the backtrace, the cause ( if gem 'cause' is used)
  #
  # @return [Hash] Returns information about the exception, like the class name, the message, the backtrace, the cause ( if gem 'cause' is used)
  def exception_data
    exception_service.merge(
      error_class: @exception.class.to_s,
      message:  @exception.respond_to?(:message) ? @exception.message : exception.inspect,
      backtrace: @exception.respond_to?(:backtrace) ? (@exception.backtrace || []).join("\n") : nil,
      cause: @exception.respond_to?(:cause) ? @exception.cause : nil
    )
  end

  # returns the instance variables defined by the exception, useful when using custom exceptions
  #
  # @return [Hash] Returns information about the instance variables defined by the exception, useful when using custom exceptions
  def exception_service
    hash = {}
    @exception.instance_variables.select do |ivar|
      attr_value = @exception.instance_variable_get(ivar)
      hash[ivar.to_s] = attr_value if attr_value.present?
    end
    hash
  end

  # returns information about URL, referer, http_method used, ip address and user agent
  #
  # @return [Hash] Returns information about URL, referer, http_method used, ip address and user agent
  def setup_env_params
    {
      url: @request.respond_to?(:original_url) ? @request.original_url : @request.path_info,
      referrer: @request.referer,
      http_method: action_dispatch? ? @request.method : @request.request_method,
      ip_address:  @request.respond_to?(:remote_ip) ? @request.remote_ip : @request.ip,
      user_agent: @request.user_agent
    }
  end

  # Filters sensitive information from parameters so that they won't get leaked into the template
  # @see AsanaExceptionNotifier::UnsafeFilter#new
  #
  # @return [Hash] Returns the information filtered , by using custom filters or the default one
  def filter_params(params)
    AsanaExceptionNotifier::UnsafeFilter.new(params, @options.fetch(:unsafe_options, [])).arguments
  end

  # returns the params sent with the initial request
  #
  # @return [Hash] Returns the params sent with the initial request
  def request_params
    @request.params
  rescue
    {}
  end

  # returns the names that will be used on the table header in the template
  # @see #fieldsets
  # @see #link_helper
  #
  # @return [String] returns the names that will be used on the table header in the template
  def fieldsets_links
    fieldsets.map { |key, _value| link_helper(key.to_s) }.join(' | ')
  end

  # returns fieldsets that will be showned in the template on separate table
  # @see #mount_tables_for_fieldsets
  #
  # @return [Array<Hash>] returns fieldsets that will be showned in the template on separate table
  def fieldsets
    @fieldsets ||= mount_tables_for_fieldsets
    @fieldsets
  end

  # returns fieldsets that will be showned in the template on separate table
  # @see #fetch_fieldsets
  # @see #mount_table_for_hash
  #
  # @return [Hash] returns the tables that will be used to render on the template as a Hash
  def mount_tables_for_fieldsets
    hash = fetch_fieldsets
    hash.each do |key, value|
      html = mount_table_for_hash(value)
      hash[key] = html if html.present?
    end
    hash
  end

  # iterates over the template params and sets the fieldsets that will be will be displayed in tables
  # @see #set_fieldset_key
  #
  # @param [Hash] hash the hash that will contain the data will be displayed in tables
  #
  # @return [void]
  def build_template_params_hash(hash)
    @template_params.each_with_parent do |parent, key, value|
      next if value.blank? || key.blank?
      parent_name = set_fieldset_key(hash, parent, 'system_info')
      hash[parent_name][key] = value
    end
  end

  # builds the template params that wil be used to construct the fieldsets and sorts them alphabetically
  # @see #build_template_params_hash
  #
  # @param [Hash] hash the hash that will contain the template params that wil be used to construct the fieldsets sorted alphabetically
  #
  # @return [Hash] returns the hash that will contain the template params that wil be used to construct the fieldsets sorted alphabetically
  def fetch_fieldsets(hash = {})
    build_template_params_hash(hash)
    hash.keys.map(&:to_s).sort
    hash
  end

  # adds the fieldsets and the fieldsets_links to the template params
  # @see #fieldsets
  # @see #fieldsets_links
  #
  # @return [void]
  def setup_template_params_for_rendering
    @template_params[:fieldsets] = fieldsets
    @template_params[:fieldsets_links] = fieldsets_links
  end

  # renders the template or the default template with the template params
  # @see #execute_with_rescue
  # @see #setup_template_params_for_rendering
  #
  # @return [void]
  def render_template(template = nil)
    execute_with_rescue do
      current_template = template.present? ? template : @template_path
      setup_template_params_for_rendering
      Tilt.new(current_template).render(self, @template_params.stringify_keys)
    end
  end

  # Creates a archive from the render_template outpout and returns the filename and the path of the file
  # @see Tempfile#new
  # @see Tempfile#write
  # @see ObjectSpace#undefine_finalizer
  # @see Tempfile#close
  # @see #tempfile_details
  #
  # @return [Array<String>] returns an array containing the filename as first value, and the path to the tempfile created as second value
  def create_tempfile(output = render_template)
    tempfile = Tempfile.new([SecureRandom.uuid, ".#{@template_details[:template_extension]}"], encoding: 'utf-8')
    tempfile.write(output)
    ObjectSpace.undefine_finalizer(tempfile) # force garbage collector not to remove automatically the file
    tempfile.close
    tempfile_details(tempfile).slice(:filename, :path).values
  end

  # Executes the fetch_archives and returns the result or empty array in case of exception
  # @see #fetch_archives
  #
  # @return [Array] returns an array with file paths to the created archives
  def fetch_all_archives
    fetch_archives
  rescue
    []
  end

  # Creates the archive, compresses it , and then removes the temporary file and splits the archive if needed
  # @see #create_tempfile
  # @see #archive_files
  # @see #remove_tempfile
  # @see #split_archive
  #
  # @return [Array] returns an array with file paths to the created archives
  def fetch_archives(output = render_template)
    return [] if output.blank?
    filename, path = create_tempfile(output)
    archive = archive_files(File.dirname(path), filename, [expanded_path(path)])
    remove_tempfile(path)
    split_archive(archive, "part_#{filename}", 1024 * 1024 * 100) # 104_857_600
  end

  # If DEBUG_ASANA_TEMPLATE is present this method will only log the path , otherwise will remove the file.
  # @param [String] path The path of the Tempfile that needs to be removed or logged
  #
  # @return [void]
  def remove_tempfile(path)
    if ENV['DEBUG_ASANA_TEMPLATE']
      logger.debug(path)
    else
      FileUtils.rm_rf([path])
    end
  end
end

#template_pathHash (readonly)

Returns The template_path that will be used to render the exception details.

Returns:

  • (Hash)

    The template_path that will be used to render the exception details



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 23

class ErrorPage
  include AsanaExceptionNotifier::ApplicationHelper

  attr_reader :template_path, :exception, :options, :template_details, :env, :request, :tempfile, :template_params

  # Initializes the instance with the template path that will be used to render the template,
  # the exception caught by the middleware and additional options sent by the middleware
  # @see #html_template
  # @see #setup_template_details
  # @see #parse_exception_options
  #
  # @param [String] template_path The template_path that will be used to render the exception details
  # @param [Exception] exception The exception that was caught by the middleware
  # @param [Hash] options Additional options that the middleware can send ( Default : {})
  #
  # @return [void]
  def initialize(template_path, exception, options)
    @exception = exception
    @options = options.symbolize_keys
    html_template(template_path)
    @template_details = setup_template_details
    @env = (@options[:env] || ENV.to_h).stringify_keys
    @request = action_dispatch? ? ActionDispatch::Request.new(@env) : Rack::Request.new(@env)
    @timestamp = Time.now
    parse_exception_options
  end

  # Initializes the instance with the template path that will be used to render the template,
  # the exception caught by the middleware and additional options sent by the middleware
  # @see #path_is_a_template
  # @see #expanded_path
  # @see #template_dir
  #
  # @param [String] path The template_path that will be used to render the exception details
  #
  # @return [void]
  def html_template(path)
    @template_path = if path_is_a_template?(path)
                       expanded_path(path)
                     else
                       File.join(template_dir, 'exception_details.html.erb')
                     end
  end

  # Returns true or false if ActionDispatch is available
  #
  # @return [Boolean] returns true if ActionDispatch::Request is defined, false otherwise
  def action_dispatch?
    defined?(ActionDispatch::Request)
  end

  # Gets the name and the extension of the template path, if was provided custom
  # ( this is needed in case someone wants something else than ERB template , since Tilt can support multiple formats)
  # @see #get_extension_and_name_from_file
  #
  # @return [Hash] Returns a hash containing the name and the extension of the template
  def setup_template_details
    template_extension = @template_path.scan(/\.(\w+)\.?(.*)?/)[0][0]
    get_extension_and_name_from_file(@template_path).merge(
      template_extension: template_extension
    )
  end

  # :reek:TooManyStatements: { max_statements: 10 }
  #
  # Fetches information about request, exception, environment and other additional information needed for the template
  # @see #fetch_basic_info
  # @see #exception_data
  # @see #setup_env_params
  # @see #filter_params
  # @see #session
  # @see #request_params
  # @see Rack::Request#cookies
  # @see ActionDispatch::Request#filtered_env
  # @see ActionDispatch::Request#filtered_parameters
  #
  # @return [Hash] Returns a hash containing all the information gathered about the exception, including env, cookies, session, and other additional information
  def parse_exception_options
    @template_params ||= {
      basic_info: fetch_basic_info,
      exception: @exception,
      request: @request,
      env: @request.respond_to?(:filtered_env) ? @request.filtered_env : @env,
      data: (@env.blank? ? {} : @env.fetch(:'exception_notifier.exception_data', {})).merge(@options[:data] || {}),
      exception_data: exception_data,
      request_data: setup_env_params,
      parameters: @request.respond_to?(:filtered_parameters) ? filter_params(@request.filtered_parameters) : filter_params(request_params),
      session: filter_params(session.respond_to?(:to_hash) ? session.to_hash : session.to_h),
      cookies: filter_params(@request.cookies.to_h)
    }.merge(@options).reject { |_key, value| value.blank? }
  end

  # returns the session from the request, (either from ActionDispatch or from Rack)
  #
  # @return [Hash] Returns the session of the request
  def session
    @request.session
  end

  # returns basic information about the system, like hostname, rails root directory, the process Id, the uname , the timestamp, and the Program name
  # @see Socket#gethostname
  # @see Rails::root
  # @see Sys::Uname#uname
  #
  # @return [Hash] Returns basic information about the system, like hostname, and other additionl information
  def fetch_basic_info
    {
      server:  Socket.gethostname,
      rails_root: defined?(Rails) ? Rails.root : nil,
      process: $PROCESS_ID,
      uname: Sys::Uname.uname,
      timestamp: @timestamp,
      pwd:  File.expand_path($PROGRAM_NAME)
    }
  end

  # returns information about the exception, like the class name, the message, the backtrace, the cause ( if gem 'cause' is used)
  #
  # @return [Hash] Returns information about the exception, like the class name, the message, the backtrace, the cause ( if gem 'cause' is used)
  def exception_data
    exception_service.merge(
      error_class: @exception.class.to_s,
      message:  @exception.respond_to?(:message) ? @exception.message : exception.inspect,
      backtrace: @exception.respond_to?(:backtrace) ? (@exception.backtrace || []).join("\n") : nil,
      cause: @exception.respond_to?(:cause) ? @exception.cause : nil
    )
  end

  # returns the instance variables defined by the exception, useful when using custom exceptions
  #
  # @return [Hash] Returns information about the instance variables defined by the exception, useful when using custom exceptions
  def exception_service
    hash = {}
    @exception.instance_variables.select do |ivar|
      attr_value = @exception.instance_variable_get(ivar)
      hash[ivar.to_s] = attr_value if attr_value.present?
    end
    hash
  end

  # returns information about URL, referer, http_method used, ip address and user agent
  #
  # @return [Hash] Returns information about URL, referer, http_method used, ip address and user agent
  def setup_env_params
    {
      url: @request.respond_to?(:original_url) ? @request.original_url : @request.path_info,
      referrer: @request.referer,
      http_method: action_dispatch? ? @request.method : @request.request_method,
      ip_address:  @request.respond_to?(:remote_ip) ? @request.remote_ip : @request.ip,
      user_agent: @request.user_agent
    }
  end

  # Filters sensitive information from parameters so that they won't get leaked into the template
  # @see AsanaExceptionNotifier::UnsafeFilter#new
  #
  # @return [Hash] Returns the information filtered , by using custom filters or the default one
  def filter_params(params)
    AsanaExceptionNotifier::UnsafeFilter.new(params, @options.fetch(:unsafe_options, [])).arguments
  end

  # returns the params sent with the initial request
  #
  # @return [Hash] Returns the params sent with the initial request
  def request_params
    @request.params
  rescue
    {}
  end

  # returns the names that will be used on the table header in the template
  # @see #fieldsets
  # @see #link_helper
  #
  # @return [String] returns the names that will be used on the table header in the template
  def fieldsets_links
    fieldsets.map { |key, _value| link_helper(key.to_s) }.join(' | ')
  end

  # returns fieldsets that will be showned in the template on separate table
  # @see #mount_tables_for_fieldsets
  #
  # @return [Array<Hash>] returns fieldsets that will be showned in the template on separate table
  def fieldsets
    @fieldsets ||= mount_tables_for_fieldsets
    @fieldsets
  end

  # returns fieldsets that will be showned in the template on separate table
  # @see #fetch_fieldsets
  # @see #mount_table_for_hash
  #
  # @return [Hash] returns the tables that will be used to render on the template as a Hash
  def mount_tables_for_fieldsets
    hash = fetch_fieldsets
    hash.each do |key, value|
      html = mount_table_for_hash(value)
      hash[key] = html if html.present?
    end
    hash
  end

  # iterates over the template params and sets the fieldsets that will be will be displayed in tables
  # @see #set_fieldset_key
  #
  # @param [Hash] hash the hash that will contain the data will be displayed in tables
  #
  # @return [void]
  def build_template_params_hash(hash)
    @template_params.each_with_parent do |parent, key, value|
      next if value.blank? || key.blank?
      parent_name = set_fieldset_key(hash, parent, 'system_info')
      hash[parent_name][key] = value
    end
  end

  # builds the template params that wil be used to construct the fieldsets and sorts them alphabetically
  # @see #build_template_params_hash
  #
  # @param [Hash] hash the hash that will contain the template params that wil be used to construct the fieldsets sorted alphabetically
  #
  # @return [Hash] returns the hash that will contain the template params that wil be used to construct the fieldsets sorted alphabetically
  def fetch_fieldsets(hash = {})
    build_template_params_hash(hash)
    hash.keys.map(&:to_s).sort
    hash
  end

  # adds the fieldsets and the fieldsets_links to the template params
  # @see #fieldsets
  # @see #fieldsets_links
  #
  # @return [void]
  def setup_template_params_for_rendering
    @template_params[:fieldsets] = fieldsets
    @template_params[:fieldsets_links] = fieldsets_links
  end

  # renders the template or the default template with the template params
  # @see #execute_with_rescue
  # @see #setup_template_params_for_rendering
  #
  # @return [void]
  def render_template(template = nil)
    execute_with_rescue do
      current_template = template.present? ? template : @template_path
      setup_template_params_for_rendering
      Tilt.new(current_template).render(self, @template_params.stringify_keys)
    end
  end

  # Creates a archive from the render_template outpout and returns the filename and the path of the file
  # @see Tempfile#new
  # @see Tempfile#write
  # @see ObjectSpace#undefine_finalizer
  # @see Tempfile#close
  # @see #tempfile_details
  #
  # @return [Array<String>] returns an array containing the filename as first value, and the path to the tempfile created as second value
  def create_tempfile(output = render_template)
    tempfile = Tempfile.new([SecureRandom.uuid, ".#{@template_details[:template_extension]}"], encoding: 'utf-8')
    tempfile.write(output)
    ObjectSpace.undefine_finalizer(tempfile) # force garbage collector not to remove automatically the file
    tempfile.close
    tempfile_details(tempfile).slice(:filename, :path).values
  end

  # Executes the fetch_archives and returns the result or empty array in case of exception
  # @see #fetch_archives
  #
  # @return [Array] returns an array with file paths to the created archives
  def fetch_all_archives
    fetch_archives
  rescue
    []
  end

  # Creates the archive, compresses it , and then removes the temporary file and splits the archive if needed
  # @see #create_tempfile
  # @see #archive_files
  # @see #remove_tempfile
  # @see #split_archive
  #
  # @return [Array] returns an array with file paths to the created archives
  def fetch_archives(output = render_template)
    return [] if output.blank?
    filename, path = create_tempfile(output)
    archive = archive_files(File.dirname(path), filename, [expanded_path(path)])
    remove_tempfile(path)
    split_archive(archive, "part_#{filename}", 1024 * 1024 * 100) # 104_857_600
  end

  # If DEBUG_ASANA_TEMPLATE is present this method will only log the path , otherwise will remove the file.
  # @param [String] path The path of the Tempfile that needs to be removed or logged
  #
  # @return [void]
  def remove_tempfile(path)
    if ENV['DEBUG_ASANA_TEMPLATE']
      logger.debug(path)
    else
      FileUtils.rm_rf([path])
    end
  end
end

Instance Method Details

#action_dispatch?Boolean

Returns true or false if ActionDispatch is available

Returns:

  • (Boolean)

    returns true if ActionDispatch::Request is defined, false otherwise



70
71
72
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 70

def action_dispatch?
  defined?(ActionDispatch::Request)
end

#build_template_params_hash(hash) ⇒ void

This method returns an undefined value.

iterates over the template params and sets the fieldsets that will be will be displayed in tables

Parameters:

  • hash (Hash)

    the hash that will contain the data will be displayed in tables

See Also:

  • ApplicationHelper#set_fieldset_key


231
232
233
234
235
236
237
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 231

def build_template_params_hash(hash)
  @template_params.each_with_parent do |parent, key, value|
    next if value.blank? || key.blank?
    parent_name = set_fieldset_key(hash, parent, 'system_info')
    hash[parent_name][key] = value
  end
end

#create_tempfile(output = render_template) ⇒ Array<String>

Creates a archive from the render_template outpout and returns the filename and the path of the file

Returns:

  • (Array<String>)

    returns an array containing the filename as first value, and the path to the tempfile created as second value

See Also:

  • Tempfile#new
  • Tempfile#write
  • ObjectSpace#undefine_finalizer
  • Tempfile#close
  • ApplicationHelper#tempfile_details


282
283
284
285
286
287
288
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 282

def create_tempfile(output = render_template)
  tempfile = Tempfile.new([SecureRandom.uuid, ".#{@template_details[:template_extension]}"], encoding: 'utf-8')
  tempfile.write(output)
  ObjectSpace.undefine_finalizer(tempfile) # force garbage collector not to remove automatically the file
  tempfile.close
  tempfile_details(tempfile).slice(:filename, :path).values
end

#exception_dataHash

returns information about the exception, like the class name, the message, the backtrace, the cause ( if gem ‘cause’ is used)

Returns:

  • (Hash)

    Returns information about the exception, like the class name, the message, the backtrace, the cause ( if gem ‘cause’ is used)



142
143
144
145
146
147
148
149
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 142

def exception_data
  exception_service.merge(
    error_class: @exception.class.to_s,
    message:  @exception.respond_to?(:message) ? @exception.message : exception.inspect,
    backtrace: @exception.respond_to?(:backtrace) ? (@exception.backtrace || []).join("\n") : nil,
    cause: @exception.respond_to?(:cause) ? @exception.cause : nil
  )
end

#exception_serviceHash

returns the instance variables defined by the exception, useful when using custom exceptions

Returns:

  • (Hash)

    Returns information about the instance variables defined by the exception, useful when using custom exceptions



154
155
156
157
158
159
160
161
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 154

def exception_service
  hash = {}
  @exception.instance_variables.select do |ivar|
    attr_value = @exception.instance_variable_get(ivar)
    hash[ivar.to_s] = attr_value if attr_value.present?
  end
  hash
end

#fetch_all_archivesArray

Executes the fetch_archives and returns the result or empty array in case of exception

Returns:

  • (Array)

    returns an array with file paths to the created archives

See Also:



294
295
296
297
298
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 294

def fetch_all_archives
  fetch_archives
rescue
  []
end

#fetch_archives(output = render_template) ⇒ Array

Creates the archive, compresses it , and then removes the temporary file and splits the archive if needed

Returns:

  • (Array)

    returns an array with file paths to the created archives

See Also:



307
308
309
310
311
312
313
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 307

def fetch_archives(output = render_template)
  return [] if output.blank?
  filename, path = create_tempfile(output)
  archive = archive_files(File.dirname(path), filename, [expanded_path(path)])
  remove_tempfile(path)
  split_archive(archive, "part_#{filename}", 1024 * 1024 * 100) # 104_857_600
end

#fetch_basic_infoHash

returns basic information about the system, like hostname, rails root directory, the process Id, the uname , the timestamp, and the Program name

Returns:

  • (Hash)

    Returns basic information about the system, like hostname, and other additionl information

See Also:

  • Socket#gethostname
  • Rails::root
  • Sys::Uname#uname


128
129
130
131
132
133
134
135
136
137
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 128

def fetch_basic_info
  {
    server:  Socket.gethostname,
    rails_root: defined?(Rails) ? Rails.root : nil,
    process: $PROCESS_ID,
    uname: Sys::Uname.uname,
    timestamp: @timestamp,
    pwd:  File.expand_path($PROGRAM_NAME)
  }
end

#fetch_fieldsets(hash = {}) ⇒ Hash

builds the template params that wil be used to construct the fieldsets and sorts them alphabetically

Parameters:

  • hash (Hash) (defaults to: {})

    the hash that will contain the template params that wil be used to construct the fieldsets sorted alphabetically

Returns:

  • (Hash)

    returns the hash that will contain the template params that wil be used to construct the fieldsets sorted alphabetically

See Also:



245
246
247
248
249
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 245

def fetch_fieldsets(hash = {})
  build_template_params_hash(hash)
  hash.keys.map(&:to_s).sort
  hash
end

#fieldsetsArray<Hash>

returns fieldsets that will be showned in the template on separate table

Returns:

  • (Array<Hash>)

    returns fieldsets that will be showned in the template on separate table

See Also:



206
207
208
209
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 206

def fieldsets
  @fieldsets ||= mount_tables_for_fieldsets
  @fieldsets
end

returns the names that will be used on the table header in the template

Returns:

  • (String)

    returns the names that will be used on the table header in the template

See Also:



198
199
200
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 198

def fieldsets_links
  fieldsets.map { |key, _value| link_helper(key.to_s) }.join(' | ')
end

#filter_params(params) ⇒ Hash

Filters sensitive information from parameters so that they won’t get leaked into the template

Returns:

  • (Hash)

    Returns the information filtered , by using custom filters or the default one

See Also:

  • UnsafeFilter#new


180
181
182
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 180

def filter_params(params)
  AsanaExceptionNotifier::UnsafeFilter.new(params, @options.fetch(:unsafe_options, [])).arguments
end

#html_template(path) ⇒ void

This method returns an undefined value.

Initializes the instance with the template path that will be used to render the template, the exception caught by the middleware and additional options sent by the middleware

Parameters:

  • path (String)

    The template_path that will be used to render the exception details

See Also:

  • #path_is_a_template
  • ApplicationHelper#expanded_path
  • ApplicationHelper#template_dir


59
60
61
62
63
64
65
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 59

def html_template(path)
  @template_path = if path_is_a_template?(path)
                     expanded_path(path)
                   else
                     File.join(template_dir, 'exception_details.html.erb')
                   end
end

#mount_tables_for_fieldsetsHash

returns fieldsets that will be showned in the template on separate table

Returns:

  • (Hash)

    returns the tables that will be used to render on the template as a Hash

See Also:



216
217
218
219
220
221
222
223
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 216

def mount_tables_for_fieldsets
  hash = fetch_fieldsets
  hash.each do |key, value|
    html = mount_table_for_hash(value)
    hash[key] = html if html.present?
  end
  hash
end

#parse_exception_optionsHash

:reek:TooManyStatements: { max_statements: 10 }

Fetches information about request, exception, environment and other additional information needed for the template

Returns:

  • (Hash)

    Returns a hash containing all the information gathered about the exception, including env, cookies, session, and other additional information

See Also:



100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 100

def parse_exception_options
  @template_params ||= {
    basic_info: fetch_basic_info,
    exception: @exception,
    request: @request,
    env: @request.respond_to?(:filtered_env) ? @request.filtered_env : @env,
    data: (@env.blank? ? {} : @env.fetch(:'exception_notifier.exception_data', {})).merge(@options[:data] || {}),
    exception_data: exception_data,
    request_data: setup_env_params,
    parameters: @request.respond_to?(:filtered_parameters) ? filter_params(@request.filtered_parameters) : filter_params(request_params),
    session: filter_params(session.respond_to?(:to_hash) ? session.to_hash : session.to_h),
    cookies: filter_params(@request.cookies.to_h)
  }.merge(@options).reject { |_key, value| value.blank? }
end

#remove_tempfile(path) ⇒ void

This method returns an undefined value.

If DEBUG_ASANA_TEMPLATE is present this method will only log the path , otherwise will remove the file.

Parameters:

  • path (String)

    The path of the Tempfile that needs to be removed or logged



319
320
321
322
323
324
325
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 319

def remove_tempfile(path)
  if ENV['DEBUG_ASANA_TEMPLATE']
    logger.debug(path)
  else
    FileUtils.rm_rf([path])
  end
end

#render_template(template = nil) ⇒ void

This method returns an undefined value.

renders the template or the default template with the template params

See Also:



266
267
268
269
270
271
272
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 266

def render_template(template = nil)
  execute_with_rescue do
    current_template = template.present? ? template : @template_path
    setup_template_params_for_rendering
    Tilt.new(current_template).render(self, @template_params.stringify_keys)
  end
end

#request_paramsHash

returns the params sent with the initial request

Returns:

  • (Hash)

    Returns the params sent with the initial request



187
188
189
190
191
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 187

def request_params
  @request.params
rescue
  {}
end

#sessionHash

returns the session from the request, (either from ActionDispatch or from Rack)

Returns:

  • (Hash)

    Returns the session of the request



118
119
120
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 118

def session
  @request.session
end

#setup_env_paramsHash

returns information about URL, referer, http_method used, ip address and user agent

Returns:

  • (Hash)

    Returns information about URL, referer, http_method used, ip address and user agent



166
167
168
169
170
171
172
173
174
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 166

def setup_env_params
  {
    url: @request.respond_to?(:original_url) ? @request.original_url : @request.path_info,
    referrer: @request.referer,
    http_method: action_dispatch? ? @request.method : @request.request_method,
    ip_address:  @request.respond_to?(:remote_ip) ? @request.remote_ip : @request.ip,
    user_agent: @request.user_agent
  }
end

#setup_template_detailsHash

Gets the name and the extension of the template path, if was provided custom ( this is needed in case someone wants something else than ERB template , since Tilt can support multiple formats)

Returns:

  • (Hash)

    Returns a hash containing the name and the extension of the template

See Also:

  • ApplicationHelper#get_extension_and_name_from_file


79
80
81
82
83
84
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 79

def setup_template_details
  template_extension = @template_path.scan(/\.(\w+)\.?(.*)?/)[0][0]
  get_extension_and_name_from_file(@template_path).merge(
    template_extension: template_extension
  )
end

#setup_template_params_for_renderingvoid

This method returns an undefined value.

adds the fieldsets and the fieldsets_links to the template params



256
257
258
259
# File 'lib/asana_exception_notifier/classes/error_page.rb', line 256

def setup_template_params_for_rendering
  @template_params[:fieldsets] = fieldsets
  @template_params[:fieldsets_links] = fieldsets_links
end