How to add some extra parameter in the airbrake parameters for JS errors - airbrake

When we are sending the airbrake error to the airbrake server, by default it includes the controller name and action name.
But the question is that I want to add some extra parameters like username, email of the current user. If anyone has any idea please suggest how to do that?
In my layout application.html:
- if ['development'].include?(Rails.env)
= airbrake_javascript_notifier
= render :partial => 'layouts/airbrake_notifier'
and in the partial I have written:
Airbrake.errorDefaults['name'] = "#{current_user.name}";<br/>
Airbrake.errorDefaults['email'] = "#{current_user.email}";<br/>
Airbrake.errorDefaults['phone'] = "#{current_user.phone}";<br/>
Airbrake.errorDefaults['title'] = "#{current_user.title;<br/>

Not a great solution, but the Airbrake Knowledge Base recommends essentially patching the airbrake gem source of the lib/airbrake/notice.rb file.
def initialize(args)
...
self.parameters = args[:parameters] ||
action_dispatch_params ||
rack_env(:params) ||
{'username' => current_user.name}
It would certainly be better to have this be configurable without patching source.
What I've done instead is simply add a few pieces of data to the session (current_user.name mainly), since session data is sent with the request. I wouldn't do this for more than a few little pieces of data.

We've just added getting current users into the Airbrake Gem.
https://github.com/airbrake/airbrake/wiki/Sending-current-user-information
You'll soon be able to sort by current user in an upcoming redesign of the UI.

Related

Extbase Hooks - execute code upon record creation

I want to create a standard typo3 extension but when I create a record (or modify it) I want to calculate something (in my case I want to call the Google Map API to get coordinates from a given address).
SO I search for a hook or something. Any idea?
One of my project example, may helps you for hook in backend when record has been changed.
In your extension file ext_localconf.php
// Hook for cancellation
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'][] = 'EXT:femanager/class.tx_femanager_tcemainprocdm.php:tx_femanager_tcemainprocdm';
hook file class.tx_femanager_tcemainprocdm.php where you can execute
your script
class tx_femanager_tcemainprocdm{
function processDatamap_postProcessFieldArray ($status, $table, $id, &$fieldArray, &$reference){
// $status also called action like delete
// $table - table name of excute backend action
// $id - record UID
// $fieldArray - fields of your table
if($table = 'your_extension_table_name'){
// your script
}
}
}
Maybe this answer is useful to you.
Register your class as a data handling hook in your extension. This one "is called AFTER all commands of the commandmap" were executed. Maybe you need to look for a more appropriate one.
Then in your registered Hook i.e. 'typo3conf/ext/your_ext/Classes/Hooks/AfterCreate.php' do your calculation. Hope this sets you on the right track.
In my special case there was no need to calculate the coordinates when the record got saved. So I just used the listAction in the controller, check if coordinates are there and if not call the Google API (and send an email if the Google API does not give a coordinate back).
In another case where the new record comes from a frontend plugin and I had to do something with this data I used the createAction in the Controller. (I am not sure if the createAction is also called when the record is created from the backend.)

Django Tastypie, Remove Elements From ManyToMany Fields

I am using Tastypie, Django for my project.
To Update a many to many field I have used save_m2m hook.
def save_m2m(self, bundle):
for field_name, field_object in self.fields.items():
if not getattr(field_object, 'is_m2m', False):
continue
if not field_object.attribute:
continue
if field_object.readonly:
continue
related_mngr = getattr(bundle.obj, field_object.attribute)
related_objs = []
print bundle.data[field_name]
for related_bundle in bundle.data[field_name]:
try:
stock = Stock.objects.get(nse_symbol = related_bundle.obj.nse_symbol)
print stock.__dict__
except Stock.DoesNotExist as e:
dataa = {"error_message": e}
raise ImmediateHttpResponse(response=HttpBadRequest(content=json.dumps(dataa), content_type="application/json; charset=UTF-8"))
related_objs.append(stock)
related_mngr.add(*related_objs)
Now I want to remove elements from the same many to many field.
How should I achieve this. Do I have to send a patch request or delete request and how to handle this.
I am begineer in tastypie. I googled it some time and I couldn't find a proper way. Please guide me how to complete this.
Thanks.
I've thought a lot about handing m2m relationships, since most of our app depends on m2m links.
I've settled for the approach of an update method. Pass in the all the references of the relationships you want changed (add and remove), then update the db accordingly. We only pass in the changed values, since if you have a paginated list, you only want to update the items the user has identified. Generally I use a custom hook for this defined in override_urls.
I used to have a separate add and remove method, which worked well until we changed the gui and allowed users simply to change checkboxes. In that approach having an update method was much more useful. You'll have to decide on which method suits your application the best.

RMagick & Sinatra: send picture to view without storing

Currently I am writing a Sinatra app that gets some pictures from user and returns a new picture.
There's part of haml form:
%input{type:'file', name:'user_image'}
And there's a code from handler: (montage is another picture)
source_userpic = params[:user_image][:tempfile]
blob = File.open(source_userpic).read
userpic = ImageList.new
userpic.from_blob(blob)
resized_img = userpic.scale(montage.columns,
montage.rows)
resized_img.opacity = MaxRGB/3
Then two images are "layered" with composite and stored (don't need)
final_picture = ImageList.new
final_picture << montage.composite(resized_img, 0, 0, OverCompositeOp)
final_picture.write("./public/uploads/#{DateTime.now}.jpg" # dirty (for example)
Next, I need to show a final_picture with ajax. There are two obvious problems: first, I don't need to save a final_picture - it's just preview, second, I must write code to avoid filenames conflicts...
How to send a final_picture to view? to_blob method? But what's next?
I solved that by using the data URI scheme.
require 'base64'
final_picture.format = "jpeg" # whatever
# Using a to_blob method to create a direct-to-memory version of the image.
# Then encode it to base64 string
data_uri = Base64.encode64(final_picture.to_blob).gsub(/\n/, "")
#image_tag = '<img alt="preview" src="data:image/jpeg;base64,%s">' % data_uri
haml:'pages/preview'
Then display a picture by
= #image_tag
Not sure if it's best solution
Take a look at Tempfile, that should take care of file name conflicts for you.
Then you could use the technique from the answers to this question, using send_file to send the tempfile.
You have to remember that the tempfile won't persist, so you have to be careful to manage that persistence if you are using different requests and responses to serve the file.

Redmine REST API called from Ruby is ignoring updates to some fields

I have some code which was working at one point but no longer works, which strongly suggests that the redmine configuration is involved somehow (I'm not the redmine admin), but the lack of any error messages makes it hard to determine what is wrong. Here is the code:
#!/usr/bin/env ruby
require "rubygems"
gem "activeresource", "2.3.14"
require "active_resource"
class Issue < ActiveResource::Base
self.site = "https://redmine.mydomain.com/"
end
Issue.user = "myname"
Issue.password = "mypassword" # Don't hard-code real passwords :-)
issue = Issue.find 19342 # Created manually to avoid messing up real tickets.
field = issue.custom_fields.select { |x| x.name == "Release Number" }.first
issue.notes = "Testing at #{Time.now}"
issue.custom_field_values = { field.id => "Release-1.2.3" }
success = issue.save
puts "field.id: #{field.id}"
puts "success: #{success}"
puts "errors: #{issue.errors.full_messages}"
When this runs, the output is:
field.id: 40
success: true
errors: []
So far so good, except that when I go back to the GUI and look at this ticket, the "notes" part is updated correctly but the custom field is unchanged. I did put some tracing in the ActiveRecord code and that appears to be sending out my desired updates, so I suspect the problem is on the server side.
BTW if you know of any good collections of examples of accessing Redmine from Ruby using the REST API that would be really helpful too. I may just be looking in the wrong places, but all I've found are a few trivial ones that are just enough to whet one's appetite for more, and the docs I've seen on the redmine site don't even list all the available fields. (Ideally, it would be nice if the examples also specified which version of redmine they work with.)

Running a premade bulletin board through my Front Controller in Zend

I tried to ask this once, but I think that my former question was too unclear for you guys to answer, so I'll try again
I'm making a website using the Zend Framework, and am trying to include the premade messageboard Phorum. So far, I've made it work by not running it through my bootstrap using my .htaccess file. What I'd like to do i'd like to do is to be able to run it through my bootstrap so that I can use my previously created Layouts and Classes that I can only run through Zend.
For example, I have a premade sign in system that works through Zend_Auth. I have the person's data saved in Zend_Session. I load the user's profile through a controller. I have a service layer for the model that connects to my database on behalf of the user. There are several other dependencies that, as far as I can tell, I need the bootstrap for.
Phorum is basically just a large set of PHP scripts that are dependent on GET parameters. My original idea had been to use a controller to render the scripts. An example of what that URI would look like is this: My-Site.com/messageboard/list.php?1,3 with messageboard being the messageboardController. While this works for loading list, it can't capture the GET parameters, which Phorum is dependent on. Due to the complex nature of Phorum, it would be nearly impossible for me to be able to go in and make it something like My-Site.com/messageboard/list/1/3 or anything along those lines. The URI has to be the former, as it is built in to Phorum.
I have tried using frames. I got to keep my log in panel up top, and had the body of the page be a frame, but it was unbookmarkable, and the back button made everything outrageously difficult. I also couldn't get the frame to talk to the parent page in Zend well, so frames aren't an option.
Does anyone have a way that I can do this? What I need, in essence, is to take the script (ex. list.php?1,3) and place whatever it would render, after having used the 1,3 parameters, into a div in the "body" div of my layout. As far as I can tell, render doesn't seem to be able to capture the GET parameters. Does anyone know of a way I can do this.
Any ideas would be immeasurably appreciated. Thank you for your help!
This isn't a trivial thing to process, however, it is possible to write a custom route, along with some controller magic to handle this sort of thing and include the proper php file:
First of all - Your route should probably be (in ZF1.9 application.ini conventions)
resources.router.routes.phorum.type = "Zend_Controller_Router_Route_Regex"
resources.router.routes.phorum.route = "messageboard(?:/(.*))?"
resources.router.routes.phorum.defaults.controller = "phorum"
resources.router.routes.phorum.defaults.action = "wrapper"
resources.router.routes.phorum.defaults.module = "default"
resources.router.routes.phorum.defaults.page = "index.php"
resources.router.routes.phorum.map.1 = "page"
Now all requests to messageboard/whatever.php should be routed to PhorumController::wrapperAction() and have 'whatever.php' in $this->getRequest()->getParam('page')
Then it should become a simple matter of redirecting your "wrapper" action to include the proper php file from phorum. I have added some code from a similar controller I have (although mine didn't include php files - it was meant solely for serving a directory of content)
public function wrapperAction() {
$phorumPath = APPLICATION_PATH."../ext/phorum/";
$file = realpath($phorumPath . $this->getRequest()->getParam('page');
if (!$file || !is_file($file)) throw new Exception("File not found");
// disable default viewRenderer - layout should still render at this point
$this->_helper->viewRenderer->setNoRender(true);
// determine extension to determine mime-type
preg_match("#\.([^.]+)$#", $filename, $matches);
switch (strtolower($matches[1]))
{
case "php":
// patch the request over to phorum
include($file);
return; // exit from the rest of the handler, which deals specifically
// with other types of files
case "js":
$this->getResponse()->setHeader('Content-Type', 'text/javascript');
ini_set('html_errors', 0);
break;
case "css":
$this->getResponse()->setHeader('Content-Type', 'text/css');
ini_set('html_errors', 0);
break;
case "html":
$this->getResponse()->setHeader('Content-Type', 'text/html');
break;
// you get the idea... add any others like gif/etc that may be needed
default:
$this->getResponse()->setHeader('Content-Type', 'text/plain');
ini_set('html_errors', 0);
break;
}
// Disable Layout
$this->_helper->layout->disableLayout();
// Sending 304 cache headers if the file hasn't changed can be a bandwidth saver
$mtime = filemtime($fn);
if ($modsince = $this->getRequest()->getServer('HTTP_IF_MODIFIED_SINCE'))
{
$modsince = new Zend_Date($modsince);
$modsince = $modsince->getTimestamp();
if ($mtime <= $modsince) {
$this->getResponse()->setHttpResponseCode(304);
return;
}
}
$this->getResponse()->setHeader('Last-Modified', gmdate("D, d M Y H:i:s",$mtime). " GMT");
readfile($fn);
}
Please - Make sure to test this code for people trying to craft requests with .., etc in the page.