Thursday, December 27, 2012

Assign class or function to Dom element on the fly

Hello Guys,
        Want to assign the class to dom element on the fly? then simply use javascript function which listed below.

demo.html

Lets assume we have anchor tag on it's click we have to apply css class.

<a id="anchor" href="" target='_blank' class='active' onclick="javascript:open_url(this.id, 'google.com');"> Open this link in new window or tab </a>

// javascript  function
<script type='javascript'>
  function open_url(id, url){
   // verify dom has 'active' class or not
   if ($('#' + id).hasClass('active')) {
     if(url != ''){
    // it's open url in new window
     window.open(url);
   }
  }
}
</script>

Thursday, December 13, 2012

Preventing Recursive Method Calls in Salesforce

Hello Guys,
        Yesterday i was playing with salesforce custom object. I had task to update the object once particular field get updated /inserted (for same object). 

Eg. I have Student__c is custom object on salesforce.

Structure of Student__c object is like:
Id, Name__c, Score_in_maths__c, Score_in_science__c, Total_score__c

So when trying to update any score value required to update Total_score__c  accordingly.  To fulfill  this i have added trigger on Student__c (after update) but it results as recursive loop.

To overcome above issue just followed the steps mention in http://blog.jeffdouglas.com/2009/10/02/preventing-recursive-future-method-calls-in-salesforce/. And it works for me.

Free feel to leave comment or ask queries. :)

Thursday, October 4, 2012

Generate chart using axlsx gem

Hello Rubies,
        I have generated the graph via axlsx gem of ruby. Follow the easy steps to generate 3D stacked bar graph.

Install axlsx gem via
   gem install axlsx

Lets, generate graph.rb file and than run ruby graph.rb

require "rubygems"
require "axlsx"

 p = Axlsx::Package.new
 wb = p.workbook

 wb.styles do |s|
    wb.add_worksheet(:name => "Bar graph demo") do |sheet|
        sheet.add_row ["A Simple Bar Chart"]
        sheet.add_chart(Axlsx::Bar3DChart, :start_at => "A1", :end_at => "F27", :grouping => :stacked, :show_legend => false, :shape => :box, :barDir => :col) do |chart|
         chart.valAxis.title = "Volumes"
         chart.catAxis.title = "Periods"
         chart.add_series :data => [1,2,3], :labels => ['Mar', 'Apr','May'], :colors => ['92D050', '92D050', '92D050']
         chart.add_series :data => [4,2,6], :labels => ['Mar', 'Apr', 'May'], :colors => ['FFFF00', 'FFFF00','FFFF00']
       end
   end  
end

file = File.open('/home/Desktop/graph.xlsx', 'w')
p.serialize(file)

Lets invoke ruby graph.rb on console and get the stacked bar chart.

Thursday, September 20, 2012

Axlsx to support line break (\n)

Hello Rubies,
      Yesterday when i was playing with axlsx gem find something interesting. Requirement is need to allow line break in content. And current axlsx gem does not support that feature. So add this patch to your existing gem or either point directly to git repository b'coze that patch is unpublished as for now.

Add this line to axlsx1.2.3/lib/axlsx/workbook/worksheet/worksheet.rb

Remove line #500  

str.gsub(/[[:cntrl:]]/,'')

and Replace with

  if RUBY_VERSION == "1.8.7"
    nasty_control_char_matcher = Regexp.new("[\x01\x02\x03\x04\x05\x06\x07\x08\x1F\v\xE2]")
  else
    nasty_control_char_matcher = Regexp.new("[\x01\x02\x03\x04\x05\x06\x07\x08\x1F\v\u2028]")
  end

  str.gsub(nasty_control_char_matcher,'')

or

gem 'axlsx', '1.2.3', :git => 'git://github.com/randym/axlsx.git'

Hope this post is useful to you folks :).

Wednesday, September 5, 2012

jumping of browser window when using cursor keys

Hello Guys,
           There is wired problem when using auto completer on page and try to use arrow key for navigation.. it simply jump the browser window.

To over come this problem just add the patch in controls.js

replace line 212 to 214 with

    if(this.index > 0) {this.index--;}
    else {
      this.index = this.entryCount-1;
      this.update.scrollTop = this.update.scrollHeight;
    }
    selection = this.getEntry(this.index);
    selection_top = selection.offsetTop;
    if(selection_top < this.update.scrollTop){
    this.update.scrollTop = this.update.scrollTop-selection.offsetHeight;
    }

replace line 217 to 220 with

    if(this.index < this.entryCount-1) {this.index++;}
    else {
      this.index = 0;
      this.update.scrollTop = 0;
    }
    selection = this.getEntry(this.index);
    selection_bottom = selection.offsetTop+selection.offsetHeight;
    if(selection_bottom > this.update.scrollTop+this.update.offsetHeight){
      this.update.scrollTop = this.update.scrollTop+selection.offsetHeight;
    }
  
add line after 297
  this.update.scrollTop = 0;

In short by replacing two functions markPrevious() & markNext() will fix our problem.

Execute raw query and manual connection

Hello Rubies,
           Some time when we have huge query that it will be easy to use RAW SQL compare to ruby's active record query.

ActiveRecord::Base.connection.query <<-END
   /* Raw sql query */
  Select * from table where conditions
END

Custom connection and query

env = RAILS_ENV
config = YAML::load(File.open('config/database.yml'))
ActiveRecord::Base.establish_connection(config[env])

schemas = ActiveRecord::Base.connection.select_values("select * from pg_namespace where nspname not in ('public','information_schema') AND nspname NOT LIKE 'pg%'").inspect

Toggle div using ruby on rails

Hello Guys,
        Toggle is the function of prototype.js. We just have to use it to perform toggling.

eg.

html = "Toggle me <span id='collapse'>"
html << link_to_function(image_tag("arrow_normal.png", :style => 'border:none;'), "$('collapse').toggle();$('expand').toggle(); new Effect.Highlight('DIVID',{endcolor:'#ffffff', startcolor:'#ffffc8', duration:2.0}); return false;")
html << "</span>"    
html << "<span id='expand' style='display:none'>"
html << link_to_function(image_tag("arrow-down.png", :style => 'border:none;'), "$('collapse').toggle();$('expand').toggle();return false;")
html << "<div id='DIVID'> HELLO </div> </span>"

Initially it show the text as Toggle me with right arrow. but when you click on that i replace the right arrow to down arrow. And display the container area with text HELLO as per above eg.

Wednesday, August 29, 2012

undefined method

Hello Guys,
            When i was trying to configure browser cms along with ruby 1.8.7 and rails 2.3.11. It raise the error like `==': undefined method `name' for "abstract":String.

Than i have find the related solution. So follow below things.

Replace method ==(other) at gems/rails-2.3.11/lib/rails/gem_dependency.rb:277

def ==(other)
   if self.respond_to?(:name) && other.respond_to?(:name)
       self.name == other.name && self.requirement == other.requirement
    else
      if other.respond_to?(:requirement)
        self.requirement == other.requirement
      else
        false
      end
    end
end

Hope this will save you life :)

Saturday, August 4, 2012

Replace double space with   in javascript

Hello Guys,
        Last time when i was playing with double spaces.. found the interesting thing. When passing the double space string from javascript (view) to controller , it converts the valid space to non-breaking space.

Lets see the eg.

View: index.rhtml

a = "This  is the pen"
a.gsub("  ", "&nbsp;&nsbsp;")

<script language='javascript/text'>
 
  /* Now assign the value to input element by */
  $('txtid').value = <%= a %>;

 // Get value back encodeURIComponent($('txtid'))

</script>
 
at controller

def any_method
   # replace '\xC2\xA0' or '&nbsp;' with ' '
   params[:a].gsub("\xC2\xA0", " ").gsub("&nbsp;", " ")
end

Hope above article is helpful to you guys.

Disable right mouse click script

Hello Guys,
        Wanna to disable the right click? Follow the below JavaScript to achieve that.

eg.
test.html

<html>
  <body>
    <div id='img'>
       <%= image_tag('https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiH4hixyVqT9hmPJ3J2xBoC7972VOGveRP864H_eGjWZyeIrzxVdHs3GgshxDAS0LdvmtzFBmSxNw8yC3Plz7zUH2fE594sKTp2FTvbaITKcM1ajz8u8GTTMbol3KXUJLs5NPtdfLqc_A/s220-h/cutex.jpeg') %>
    </div>
  </body>
 
  <script language="javascript" type="text/javascript">
 
   // Disable right click 
   var message = "you can't right click on image";

   function clickIE4(){
     if (event.button == 2) {
        return false;
    }
  }

  function clickNS4(e){

    if (document.layers || document.getElementById && !document.all) {
   
      if (e.which == 2 || e.which == 3) {
          return false;
      }
    }
  }

  if (document.layers) {
    document.captureEvents(Event.MOUSEDOWN);
    document.onmousedown = clickNS4;
  }
  else
    if (document.all && !document.getElementById) {
      document.onmousedown = clickIE4;       
    }

   document.oncontextmenu = new Function("alert(message); return false")
  </script>
</html>

Friday, July 27, 2012

Arbitrary precision decimal floating-point type for Ruby

Hello Rubies,
           Accurately convert numbers  to decimal or exact precision point. Use the Flt gem do discover the below scenario. 

Flt::DecNum is a standards-compliant arbitrary precision decimal floating-point type for Ruby. It is based on the Python Decimal class. 

Usage:

sudo gem install flt

require 'flt'
include Flt
 
x = 0.00000020586
y = Flt::DecNum(x.to_s)
Flt::DecNum.context.precision = 2
puts y/Flt::DecNum(1)

result should be 2.1E-7

For more information just follow the http://flt.rubyforge.org/.

Thursday, July 26, 2012

Import csv file using ruby processor

Hello Guys,
        Let's discuss how to import .csv file into database using ruby processor.

Read the .csv file:

require 'fastercsv'

rows = CSV.read("#{RAILS_ROOT}/test.csv")
header = rows[0]
rows[1..-1].each do |row|
    data = {}
    header.each_with_index do |key, index|
      data[key.downcase] = row[index].strip
    end
    ModelObject.create!(data)
end

test.csv looks like

No,Name,Percentage
1,Priyanka,81
2,Rahul,82
3,Ruby,75

Wednesday, July 25, 2012

Cannot deserialize instance of date from VALUE_STRING on salesforce

Hello Guys,
        I am working on salesforce from past few days. Just discover the bug related to date field setting using databasedotcom gem. When we are setting date value using ruby 1.9.2 it works as per expectation but with ruby 1.8.7 it gives error like 'Cannot deserialize instance of date from VALUE_STRING value'. To resolve this issue need to install latest gem version databasedotcom-1.2.7.

See this thread on github to get more detail

Monday, July 23, 2012

Generate Rss feed with rails application

  Hey guys,
      Lets today we create the rss feed with our existing rails application. Consider we have controller called post and have index method to show all the available posts. Now meanwhile we need to create feed for available posts as well.

controller:

def index
  @posts = Post.find(:all, :order => "created_at desc")
  respond_to do |format|
     format.html { render :template => 'posts/index.rhtml' }
     format.xml { render :template => 'posts/index.rxml', :layout => false
        headers["Content-Type"] = "application/rss+xml"
     }
  end
end

view:

index.rxml

xml.instruct!
xml.rss "version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/" do
  xml.channel do
    xml.title 'Available Posts'
    xml.description h("Here is the posts ... blah blah")
   
    @posts.each do |post|
      xml.item do
        xml.title post.title
        xml.link url_for(:only_path => false,
          :controller => 'posts',
          :action => 'show',
          :fishery => post.id)
        xml.description post.description
        xml.pubDate CGI.rfc1123_date(post.created_at)
      end
    end
  end
end

index.rhtml

# Add auto discovery tag to access rss feed

<%= auto_discovery_link_tag :rss, {:controller => "posts", :action => "index"}%>

See your rss feed for posts is ready!! Whenever auto discovery tag found it enables the rss icon on browser. Keep in mind Either you have to use predefined xml node or need to create XSL template. You can also emend the stylesheet into XSL template.

Thursday, July 19, 2012

Get the Date difference in days

Hello guys,
        Wanna to get the date difference in terms of days?

eg.
date_x = Time.now.to_date
date_y = Date.parse('2012-05-20')

passed_days = (date_x.to_date - date_y.to_date).to_i

passed_days should give the date difference in days.

Thursday, July 5, 2012

Convert string to serialize hash

Hello Rubies,
        Do you phase the problem ? - sometime  when we are retrieving the serialized hash field from table we might get string as response. So in that case you can use one of the below solutions.

Eg. 

Model - User.rb
class User < ActiveRecord::Base
   serialize :content, Hash
end

convert string to serialize hash format by 

# get the one of the record from users table
user = User.first

either using
    user.content.to_yaml
or
    YAML.parse(user.content)
or
    YAML.load(user.content)

Wednesday, June 20, 2012

Ajax request via javascript

Hello Rubies,
      Have you tried AJAX request via javascript? Lets see the eg.

<script type="text/javascript">

  // Ajax without update parameter:
  function ajax_request(id){
    window._token = '<%= form_authenticity_token %>';
    var url = '/controller/action';
    var pars = 'id=' + id + '&authenticity_token=' + window._token;
    var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onFailure: showFailure(), onSuccess: showSuccess() });
  }

  // Ajax with update parameter:
  function ajax_update_request(id){
    window._token = '<%= form_authenticity_token %>';
    var url = '/controller/action';
    var pars = 'id=' + id + '&authenticity_token=' + window._token;
    var myAjax = new Ajax.Updater('update_div_id', url, {method: 'get', parameters: pars, onFailure: showFailure(), onSuccess: showSuccess()});
  }

  function showSuccess(){
  }

  function showFailure(){
  }

</script>

Tuesday, June 19, 2012

Disable the link in rails via css or javascript

Hello Rubies,
      We have facility to disabled the link in rails 3 using :disable_with => 'Blah...'. But what about rails lowest version? We have one of the two possible option.

Either use:
1. <a href="javascript:;"> blah blah </a>
or
2. in css define
 .disabled_link{
   cursor: default;
   pointer-events: none
;
 }
<a class='disabled_link'> blah blah </a>

Friday, June 15, 2012

Implement tab side out

Hello Guys,
      To implement tab slide out along with you application use the below code.


Download 2 javascript files:
1. jquery.min.js
2. tabSlideOut.v1.3.js


In your html page simply add below code.


<html>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
    <script src="http://www.building58.com/examples/js/jquery.tabSlideOut.v1.3.js"></script>
  </head>
 
  <body>
    <script type="text/javascript">
      $(function(){
       jQuery('.slide-out-div').tabSlideOut({
 
         tabHandle: '.handle', //class of the element that will become your tab
         pathToTabImage: 'http://www.building58.com/examples/images/contact_tab.gif',
         //path to the image for the tab //Optionally can be set using css
         imageHeight: '190px', //height of tab image           //Optionally can be set using css
         imageWidth: '59px', //width of tab image            //Optionally can be set using css
         tabLocation: 'left', //side of screen where tab lives, top, right, bottom, or left
         speed: 300, //speed of animation
         action: 'click', //options: 'click' or 'hover', action to trigger animation
         topPos: '100px', //position from the top/ use if tabLocation is left or right
         leftPos: '20px', //position from left/ use if tabLocation is bottom or top
         fixedPosition: false //options: true makes it stick(fixed position) on scroll
       });
 
      });

     jQuery.noConflict(); // use this when prototype will be conflict with jquery.
 
    </script>

    <style type="text/css">
     
      .slide-out-div {
          padding: 20px;
          width: 250px;
          background: #ccc;
          border: 1px solid #29216d;
      }
    </style>

    <div class="slide-out-div">
      <a class="handle" href="javascript:;">Content</a>
      <h3>Contact Us</h3>
      <p>
        Click on here to contact us..blah..blah..
      </p>
    </div>
  </body>

</html>

Monday, June 11, 2012

Concat string via MY SQL & PSQL

Hey guys,
      Do you know there is little bit difference to concat the string  under MY SQL & PSQL?

mysql:

update posts set title = concat(title, 'Hey')

psql:

update posts set title = title || 'Hey'


Schedule cron job on linux

Hello Guys,
   Set cron job on linux to invoke at every 1 minute or daily base.

on command prompt:

crontab -e

add below lines

For every 1 minute:

 */1 * * * * cd /home/user/application_path && /home/user/.rvm/bin/rvm use ruby-1.9.2-p136 rake custom_task >> /home/user/crontab_errors.txt

For daily

0 0 * * * cd /home/user/application_path && /home/user/.rvm/bin/rvm use ruby-1.9.2-p136 rake reminder_email >> /home/user/crontab_errors.txt

Friday, June 8, 2012

rake jobs:work fails - delayed_job

 Hello Guys,
       Do you stuck with the problem to execute rake jobs:work during delayed_job implementation? than follow the below steps.
 Rake.rb
In your rails application's Rakefile add few lines.

begin
  gem 'delayed_job', '~>2.0.5'
  require 'delayed/tasks'
rescue LoadError
  STDERR.puts "rake gems:install` to install delayed_job"
end

Also if you want to use the script/delayed_job start command than add delayed_job under lib folder of rails application.

lib/delayed_job

#!/usr/bin/env ruby

require File.expand_path(File.join(File.dirname(__FILE__), '.', 'config', 'environment'))
require 'delayed/command'
Delayed::Command.new(ARGV).daemonize


Now, you do the rake -T to see that delayed_job task are also embed. Hope you will find useful support via this post.

Wednesday, April 25, 2012

Dygraph fails on IE 8

Hello Guys,
      Just discover the problem while loading dygraph on IE 8. There are possible scenarios for dygraph failure.

case 1. instanceof is not support
           replace instanceof with Object.prototype.toString.call()
           Line 500 of dygraph-utils.js replace
              typeof Node === "object" ? o instanceof Node :
           with
              typeof Node === "object" ? Object.prototype.toString.call(o) === Node :

case 2. canvas can't load

<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7; IE=EmulateIE9">
<!--[if IE]><script src="excanvas.js"></script><![endif]-->
<!--[if lt IE 9]><script language="javascript" type="text/javascript" src="http://mycheckpoint.googlecode.com/svn-history/r95/trunk/dygraphs/excanvas.min.js"></script><![endif]-->


Hope above article will help you.

Thursday, April 19, 2012

Configure mailer with ruby

Hello Rubies,
    As we have to send the mail from rails application for that it requires to set the mailer configuration with rails.

First you have to install the package called 'sendmail'
sudo apt-get install sendmail

Now in environment.rb file of rails application set below code:

ActionMailer::Base.delivery_method = :sendmail

config.action_mailer.smtp_settings = {
  :address => "smtp.gmail.com",
  :port => 587,
  :domain => 'test.com',
  :authentication => :plain,
  :user_name => 'XYZ@gmail.com',
  :password => 'PWD' 
}

Hope this post will help you.

Tuesday, April 17, 2012

Number of days between two dates

Hello Rubies,
    Get the days between two dates using below method of ruby date class.

Lets consider we have date range like
date1 = Date.today.to_date
date2 = 1.year.ago.to_date
no_of_days = date1.mjd - date2.mjd

Hope this simple method of ruby date class will help you out to find days between to dates.

Friday, April 6, 2012

Combination of array element

Hello Guys,
    Want the combination of array elements using ruby? than use the below custom method.

def arr_combine(arr_1, arr_2)
    return arr_1 if arr_2.empty?
    arr_3 = []
    arr_1.each do |e1|
      arr_2.each do |e2|
        arr_3 << [e1, e2].flatten
      end
    end
    return arr_3
  end

eg. we have array like arr = [[1,2], [3,4,5]]
we expect the result as [[1,3],[1,4],[1,5],[2,3],[2,4],[2,5]] than simply invoke the above method by passing each element of given array.
arr_combine(arr[0], arr[1]) gives you required outcome.

Hope this post will help you out.

Friday, January 20, 2012

Randomly generate string


Hello Guys,
        If you want to generate random string with specific some constraint like at least single upper case, lower case and digit. or many more.


Here i have found gem called 'passgen'. which provides many possible changes.
gem install passgen


On console:
require 'rubygems'
require 'passgen'
Passgen::generate(:lowercase => true, :uppercase => true, :digits => true, :length => 10)


For more information follow the url - https://github.com/cryptice/Passgen

Wednesday, January 4, 2012

Undefined method Object.keys


Hello Guys,
        Object.keys is depreciated and it does not support in some of the browsers like IE, FF 3.x. So we have to add the javascript object.keys method to overcome this problem.

Object.keys = function(obj) {
   if (typeof obj != "object" && typeof obj != "function" || obj == null) {
     throw TypeError("Object.keys called on non-object");
   } 
   var keys = [];
   for (var p in obj) obj.hasOwnProperty(p) && keys.push(p);
   return keys;
}

Now see we resolve the javascript error 'Undefined method Object.keys'.

Duck Typing in Ruby

Hello Rubies,
       Ruby is an object oriented programing language. we don't declare the data type of variables or methods - everything is treated as object. Ruby supports feature called 'duck typing'. Duck typing more concern about what's the behavior of method and what methods can be called on it.

For eg.
We create the simple method to do the multiplication of two arguments. As in ruby we didn't define the data type. So it return the output of method in requested method format.

def calculate(a, b)
  return a * b
end

case a. 
   Pass integer as argument
   calculate(2, 3) => 6
case b.
   Pass string as argument
   calculate('Ruby on ', 'Rails') => Ruby on Rails

So as per argument type it return back the result in requested format. So this is the concept of duck typing. 
If we have to implement same functionality using java than it requires to define methods as per requested type. so when we invoke the method than it first match argument type than return the appropriate result. 

So now you know how cool is ruby than java ;)

Monday, January 2, 2012

Accept argument during .sql file invocation

Hello,
        Some time we have to set the variable of .sql file run time. In that case require to take input and set the variable accordingly.

For eg. There is sql file called 'tablefunc.sql' in which default search_path is set to public but we require it to be dynamic. Now we need to execute the .sql file as

In .sql file
SET search_path = :search_path;

Invoke sql file using system command
config = YAML::load(File.open('config/database.yml'))
pg_schema = 'demo'

system("psql -U #{config[env]['username']} -d #{config[env]['database']} --variable search_path=#{pg_schema} < lib/tablefunc.sql")