How to add bookmarklet??

The following code help you to add bookmarklet to other site……………….

javascript:(function(){
if(document.getElementById) 
{var x=document.getElementsByTagName(‘head’).item(0);
 var o=document.createElement(‘script’); 
if(typeof(o)!=’object’) o=document.standardCreateElement(‘script’); 
o.setAttribute(‘src’,'http://………………………./javascripts/mr.js’);   
o.setAttribute(‘type’,'text/javascript’)
if (document.getElementById(“divAddToMyregistry_Panel_Container”)) {
CreateDiv_AddToMyregistry();
}
else {
var documentBody = document.getElementsByTagName(“body”)[0];
var Divform = document.createElement(‘div’)
Divform.id = “popup_name”
Divform.className =”bookmark_popup_block”
documentBody.appendChild(Divform)
var Div_own = document.getElementById(‘popup_name’)
var Divform2 = document.createElement(‘div’)
Divform2.id = “bookmark_content”
Div_own.appendChild(Divform2)
var MrOtherStores1 = document.createElement(‘link’);
MrOtherStores1.rel = “stylesheet”;
MrOtherStores1.type = ‘text/css’;
MrOtherStores1.href = “http://………………./stylesheets/bookmark.css”;
documentBody.appendChild(MrOtherStores1);
// Check Price
var MrOtherStoresPrice = document.createElement(‘script’);
MrOtherStoresPrice.id = “mr_scriptGetPrice”;
MrOtherStoresPrice.type = ‘text/javascript’;
MrOtherStoresPrice.src = “http://……………/javascripts/jquery.js”;
documentBody.appendChild(MrOtherStoresPrice);
var newScript1 = document.createElement(‘script’);
newScript1.id = “pt_scriptAuthentication”;
newScript1.type = ‘text/javascript’;
newScript1.src = “http://………………………………/javascripts/jquery.xdomainajax.js”;
documentBody.appendChild(newScript1);
var drag_script = document.createElement(‘script’);
drag_script.id = “drag_script”;
drag_script.type = ‘text/javascript’;
drag_script.src =”http://…………………./javascripts/event_drag.js”;
documentBody.appendChild(drag_script);
// Check Cookie
var newScript = document.createElement(‘script’);
newScript.id = “mr_scriptAuthentication”;
newScript.type = ‘text/javascript’;
newScript.src = “http://…………………../javascripts/bookmark.js”;
documentBody.appendChild(newScript);

jQuery(document).ready(function() {
var popID = “popup_name” //jQuery(this).attr(‘rel’); //Get Popup Name
var popURL = “#?w=685″ //jQuery(this).attr(‘href’); //Get Popup href to define size
//Pull Query & Variables from href URL
var query= popURL.split(‘?’);
var dim= query[1].split(‘&’);
var popWidth = dim[0].split(‘=’)[1]; //Gets the first query string value
//Fade in the Popup and add close button
jQuery(‘#’ + popID).fadeIn().css({
‘width’: Number( popWidth )
}).prepend(‘<img src=”http://………………………./images/lightview/close_small.png” alt=”Close” />’);
jQuery(‘#popup_name’).bind(‘drag’, function(event){
jQuery(this).css({
top: event.offsetY,
left: event.offsetX
});
});
////Close Popups and Fade Layer
jQuery(‘.book_close, #fade’).live(‘click’, function() { //When clicking on the close or fade layer…
jQuery(‘#fade, .bookmark_popup_block’).fadeOut(function() {
jQuery(‘#fade, .book_close’).remove();  //fade them both out
});
return false;
});
var d = document
var w = window
var e = w.getSelection
var k = d.getSelection
var x = d.selection
var s = (e?e():(k)?k():(x?x.createRange().text:0));
var f = “http://……………………/item_from_bookmarklet”;
var l = d.location
e = encodeURIComponent
var p= ‘?v=1&u=’+ e(l.href)%20 + ‘&t=’ + e(d.title.replace(/^\s*|\s*$/g,”))%20 + ‘&s=’+ e(s);
var loadUrl=f;
jQuery.ajaxSetup({
cache: false
});
var ajax_load = “<img src=’img/load.gif’ alt=’Loading…’ />”;
jQuery(“#bookmark_content”).html(ajax_load).load(“http://…………………………/item_from_bookmarklet?” + “u=”+ encodeURIComponent(l.href) +”&”+”s=”+ s + “&t=” + encodeURIComponent(d.title), null, function(responseText){
jQuery(‘#bookmark_content’).prepend(responseText);
});
});
Advertisements

How to solve delayed_job running problem in server machine?

If there is problem of running delayed job in your server machine then install “daemon-spawn” plugin and change the delayedjob script file as following…………..

require 'rubygems'

require 'daemon-spawn'

RAILS_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..'))
class DelayedJobWorker < DaemonSpawn::Base
def start(args)
ENV['RAILS_ENV'] ||= args.first || 'development'
Dir.chdir RAILS_ROOT
require File.join('config', 'environment')
Delayed::Worker.new.start
end
def stop
system("kill `cat #{RAILS_ROOT}/tmp/pids/delayed_job.pid`")
end
end
DelayedJobWorker.spawn!(:log_file => File.join(RAILS_ROOT, "log", "delayed_job.log"),
:pid_file => File.join(RAILS_ROOT, 'tmp', 'pids', 'delayed_job.pid'),
:sync_log => true,
:working_dir => RAILS_ROOT)

The RAKE task for this is bellow……………………………………….


desc "Start delayed_job process"

task :start_job, :roles => :app do

run "cd #{current_path}; chmod 755 script/delayed_job; RAILS_ENV=#{env} script/delayed_job start"

end

desc "Stop delayed_job process"

task :stop_job, :roles => :app do

run "cd #{current_path}; chmod 755 script/delayed_job; RAILS_ENV=#{env} script/delayed_job stop"

end

Using re-captcha in Rails application

Captcha validation is implemented in rails app using “ambethia-recaptcha” gem. After installing the gem you need to do the following…..

You need to register in google recaptcha group which provides you 2 keys and put these 2 keys in your environment.rb file as follows

ENV['RECAPTCHA_PUBLIC_KEY']  = '6LffcrsSA...................................''
ENV['RECAPTCHA_PRIVATE_KEY'] = '6LffcrsSA.................................'

You just need to do the following code in your view if you want to show the default recaptcha…

=recaptcha_tags( )

If you want to customize it then write the following code in your view…

=recaptcha_tags( :display => {:theme => 'custom', :custom_theme_widget => 'recaptcha_container'})

#recaptcha_container

#recaptcha_image

%input#recaptcha_response_field.text{ :name => "recaptcha_response_field", :type => "text" }

%label{ :for => "recaptcha_response_field" }

(Enter the two words above)

%p

Choose captcha format:

%a.btn_img{ :href => "javascript:Recaptcha.switch_type('image');",:title => 'Image' }

or

%a.btn_audio{ :href => "javascript:Recaptcha.switch_type('audio');",:title => 'Audio' }

/%input#recaptcha_reload_btn{ :type => 'image', :src => '/images/home/refresh.gif', :style=>'width: 18px; height:15px',:value => 'New', :onclick => "Recaptcha.reload();" }

%script{ :src => "http://api.recaptcha.net/challenge?k=#{ENV['RECAPTCHA_PUBLIC_KEY']}", :type => "text/javascript" }

%noscript

%iframe{ :src => "http://api.recaptcha.net/noscript?k=#{ENV['RECAPTCHA_PUBLIC_KEY']}" }

/height="300" width="500" frameborder="0">

%textarea{ :name => "recaptcha_challenge_field", :rows => "3", :cols => "40" }

Then for validation you have to write code in your controller..........
if verify_recaptcha(:model => @user, :message => "Oh! It's error with reCAPTCHA!")
//
end

Creating direction from source to destination in Google Map using Rails

Google map in Rails application is implemented by YM4R  gem/ ym4r_gm plugin. Suppose anyone one to see direction in Google Map From his address to destination address by clicking his city point in Map. The following code in Ruby on Rails do that with a bit of JavaScript function...........
def initiate_map fromadd , toadd
@map = GMap.new("map_div");
@map.control_init(:large_map  => true,:map_type => true)
@map.center_zoom_init([38.957101, -95.251469],4)
@map.overlay_init(GMarker.new(fromadd))
@map.event_init(@map, :dblclick,"function(marker,address){ if (marker)
{map.removeOverlay(marker); } else {
var gdir;
gdir  = new GDirections(map, document.getElementById('directions'));
gdir.load('from: ' + '#{fromadd}' + ' to: ' + '#{toadd}');
}}" )
end
Now for dynamically updating the direction do the following code….

def initiate_map1 fromadd , toadd
@map=GMap.new('map_div')
@js_str = "var geocoder = new GClientGeocoder(); \n"+
"geocoder.getLatLng( '#{MappingObject.javascriptify_variable(fromadd)}',function(point) {
map.setCenter(point, 13);
var marker = new GMarker(point);
map.addOverlay(marker);
marker.openInfoWindowHtml('#{MappingObject.javascriptify_variable(fromadd)}');
}) ; \n" +
"GEvent.addListener(map, \"click\", function(address) { var gdir  = new GDirections(map, document.getElementById('directions'));
gdir.load('from: ' + '#{MappingObject.javascriptify_variable(fromadd)}' + ' to: ' + '#{MappingObject.javascriptify_variable(toadd)}');});"
end

After that you have to write  page << @js_str in a js tempalte. In the view write this code

=GMap.header
=@map.to_html
=@map.div(:width => 600, :height => 400)
.directions

All is done. 

Auto-escaping HTML with Rails in the model level for protecting script injection

We can sanitize an input field data easily before saving or before displaying it in Rails. In this case we don’t need to h function in the view level. We can do it at each model by using plugin.

xss-terminate is a plugin  that makes stripping and sanitizing HTML stupid-simple, => http://github.com/look/xss_terminate , here we can find plugin. But currently it can’t be installed directly, so we have to download it and unpack its contents in a folder named “xss_terminate” under vendor/plugins folder.

Suppose we want to sanitize any script before saving an user name in user model so we have to just write the following code……

class User < ActiveRecord::Base
xss_terminate  :sanitize=>[:user_name]

...

.....
end

We can also avoid any field from sanitizing by “:except” option as follows..

xss_terminate  :except => [:address]

More on…..

http://railspikes.com/2008/1/28/auto-escaping-html-with-rails

How we do A/B testing in Rails

Configuration

For A/B testing in Rails there is a gem named vanity. At first we have to install the vanity gem by the command=> gem install vanity. After that we have to just configure the test.rb file under the “/environments” folder as follow…

config.after_initialize do
require "vanity"
Vanity.playground.test!
end

Be careful this code must be written at the end of the file. Here we used Vanity.playground.test!  for not accessing the redis for storing data. But if we want to access redis then we have to configure as follows…

Vanity.playground.redis = "::15" # Different DB
Vanity.playground.redis.flushdb # Do this before running tests

Add a new controller for Vanity:

class VanityController < ApplicationController
include Vanity::Rails::Dashboard
end

Lets write a test code  ===>

Now our A/B test file should be under the “experiments/” folder. Lets see a sample code

ab_test "Customer Message without Pricing" do
 description "Testing to see if messages without pricing increases number of signups."
 metrics :trial_activation
end

Here the name of the metric parameter is same as the name of the file where our actual experiment is done under the “experiments/metrics/” directory. The following code is contained in the trial_activation.rb file.

metric "Signup for trial" do
 description "Measures how many people signed up to try our awesome service."
 model Account.in_trial
end

Basic about Object Oriented JavaScript

JavaScript has nice and special object-oriented features. Discussion about some of these features are…….

(1) JavaScript Object

Object in JavaScript is not same as C#, Java. JavaScript object is called a name-value pair i.e just like {“name” : “value”}. A function in JavaScript is basically an object function. Example…..

  • var motor = { “Name” : “Honda” };
  • alert( motor.Name ); // output is Honda.

(2)Instantiating Object

In JavaScript an object is instantiated by calling function with the new operator. This is done by following way…..

  • function Car(name) {
  • this.name=name;
  • }
  • var motor = new Car(“Honda”);

(3) Prototype object

An object is a copy of existing example (prototype) object. Any properties and method of the prototype object also appear in the created object. That means created object inherits the properties and method of the prototype object. Every constructor function/object has property name “prototype” and this prototype object has a property called “constructor”. Constructor property indicates the base constructor function. One thing need to remember that “constructor” is not the own property of created object. In JavaScript “Object.prototype” is the ultimate base prototype of  all prototypes.

(4)Static members

A member declared in a function object  associated with the function name is called static member of the object. The calling of the static member/function is same as Java.

  • function Car() {
  • Car.name= function(){
  • return “Motor”;
  • };
  • }
  • Car.name();

(5)Concept of closure

Anonymous inner function is treated as closure in JavaSript because the inner function closes over the environment (the arguments and local variables of the outer function) in which it is defined. Closure in JavaScript is used for simulating private members. See the following….

  • function Check (upperbound) {
  • return function (lowerbound ) {
  • return (upperbound>lowerbound) ? true : false;
  • };
  • }
  • var bigger =  Check (100);
  • alert(bigger(90));  // return true.


(6) Accessing Private Members

Normally local variables of a function can’t be accessed outside the function. But in JavaScript local variable can be accessed through inner function’s closure.

(7) Inheriting classes

Properties of one class(prototype) is inherited by another class(prototype) only by constructor function. Lets see it in following…..

  • function vehicle {
  • //
  • }
  • function car {
  • //
  • }
  • car.prototype = new vehicle();

Here, car inherits the vehicle class.

(8) Namespaces

Namespaces in JavaScript is used for creating JavaScript library. In the following way we can build Namespaces for prototype classes…..

  • var namespace={ };
  • namespace.ClassPrototype = function() {
  • //
  • };

Read the rest of this entry »