Friday, 19 December 2014

Ading buttons and action Active admin

Active Admin is a framework for creating administration style interfaces. It abstracts common business application patterns to make it simple for developers to implement beautiful and elegant interfaces with very little effort.

1. Adding custom buttons: if you want to add custom buttons for any resource then add the following code inside the 'admin/resource.rb'

  action_item do
    link_to "something_text" path_for _action, :method => :method_type(get or post)
  end

2.Adding custom actions: if you want to add custom action for active admin then add following code inside AdminController

def action_name
// your source code here
end

3. Adding routes for custom controller: Add routes for your action inside routes.rb file like



Friday, 21 November 2014

Adding a crontab in ubuntu by capistrano task using Rails Application

How ever in practice sometimes we required to add a cronjob while deployment of the rails application.here an example of replace an exiting or create a new crontab by capistrano task.have a look:

there are following steps to reached to the required result.these are:

1. Create a recipe named 'cron.rb' inside the 'config/recipes' folder.
2. Add the following code to that 'cron.rb'

namespace :crontab do
  desc "Install cronjobs"
  task :install, roles: :desired_role do
    template "crontab.erb", "/tmp/cronjob"
    run('crontab /tmp/cronjob')
  end
  after "deploy:cold", "crontab:install"
end

// if you are dealing with multiple servers and want to add crontab on only one server then add an extra role to that server/machine in 'config/environment.rb' like

server 'ip_of_the_server', :web, :app, :db, :role_for_cron, primary: true 
example:

server 'ip_of_the_server', :web, :app, :db, :cron, primary: true

modify 'cron.rb' like this:


namespace :crontab do
  desc "Install cronjobs"
  task :install, roles: :cron do
    template "crontab.erb", "/tmp/cronjob"
    run('crontab /tmp/cronjob')
  end
  after "deploy:cold", "crontab:install"
end


3. Create a template named 'crontab.erb' inside 'config/recipes/templates'.
// dont forget to require 'crontab.erb'  into your deploy.rb file.

4. Add cronjob into 'crontab.erb'.for this add the following code in 'crontab.erb'

* * * * * /bin/bash -l -c "cd <%= current_path %> && bundle exec rake_path task_namesapce:task_name RAILS_ENV=rails_env" >

example,

* * * * * /bin/bash -l -c "cd <%= current_path %> && bundle exec /home/<%= user %>/.rvm/rubies/ruby-2.1.2/bin/rake test_task:test RAILS_ENV=<%= rails_env %>" >> <%= current_path %>/crontab.txt

// this above cronjob will execute every minute every hour and when it execute add an entry to 'crontab.txt' file.

5. Customizing you cronjob execution delay:

you can customize your cronjob execute delay.as example:

*/5 * * * * // before cronjob will execute job every five minute 
delay.

 





Friday, 7 November 2014

Sending emails in Rails using sendgrid

In most of the application you need to send bulk or single emails on a periodic time.like newsletter or digest or any other thing.for sending emails in your rails application you use SMTP servers to send emails.here is an example of sending emails by using sendgrid:

1). First of all you have to create a sendgrid account and make it provisioned.for sign-up in send grid you have to give a website(domain name) for the provision.if your website doesn't have enough content then your account can't be provisioned.
you will not able to send emails from sendgrid if your account is not provisioned.  

2). Goto https://sendgrid.com/developer after you logged in to your sendgrid account and copy SMTP settings.

3). In your environment.rb write the following settings:

 # Action mailer settings
  config.action_mailer.default_url_options = {:host => 'your_host_name(domain_name)'}

  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
      :user_name => 'user_name',
      :password => 'your_password',
      :address => 'smtp.sendgrid.net',
      :port => 587,
      :authentication => :plain,
      :enable_starttls_auto => true
  }

now you emails sent from your application will be delivered via sendgrid.com

Handling Email Activity: 

you can login to your sendgrid account and see email activities.

1). Handling Bounce Emails: if you want to handle bounced emails then there are two ways to do:
a). Forword emails to a perticular email_id: if you want to send the bounced emails to another email-id then follow these steps:

click Email Reports ->Bounces -> settings

in the setting page click the check box and give the email-id on which you want to receive the bounced emails.

2). Handle post request from sendgrid: The other way to enable Event Notification and click on settings. on the settings page give an url and select events. when any of the selected event occur sendgrid send a post request on the given url with all possible parameters(ex. bounced,drop email information's). 

the url which you give above have to manage the post request.


Saturday, 1 November 2014

Immutable Objects with Object.freeze

One of the more common techniques in JavaScript is the use of an object to hold configuration values. The object might be accessed as a global or passed around as an argument. For example:

var artist = {
    name: "Johnny Cash",
    latestAlbum: "American V"
};

function announce (artist) {
    if (artist.name == "Johnny Cash") {
        console.log("Hello Johnny");
    } else {
        console.log(artist.name);
    }
}
announce(artist);
// Outputs: "Hello Johnny"

console.log(artist);
// Outputs: {
//     name: "Johnny Cash",
//     latestAlbum: "American V"
// }

But in either sort of situation, there is a problem. Functions that have access to the configuration object can modify the object, whether intentionally or accidentally. Suppose that you had a coworker modify the announce function above to highlight Elvis rather than Cash, but they mistyped the comparison.

var artist = {
    name: "Johnny Cash",
    latestAlbum: "American V"
};

function announce (artist) {
    // Whoops! Assigning the name rather than testing equality!
    if (artist.name = "Elvis Presley") {
        console.log("The King");
    } else {
        console.log(artist.name);
    }
}

announce(artist);
// Outputs: "The King"

console.log(artist);
// Outputs: {
//     name: "Elvis Presley",
//     latestAlbum: "American V"
// }

The Object.freeze method takes an object and renders it effectively immutable. Its existing properties may not be modified and new properties may not be added. In the example above this means that even though the logical error is still there, our artist object remains safe from modification and available for later use.
example:

var artist = {
    name: "Johnny Cash",
    latestAlbum: "American V"
};

Object.freeze(artist);

function announce (artist) {
    // Whoops! Assigning the name rather than testing equality!
    if (artist.name = "Elvis Presley") {
        console.log("The King");
    } else {
        console.log(artist.name);
    }
}

announce(artist);
// Outputs: "The King"

console.log(artist);
// Outputs: {
//     name: "Johnny Cash",
//     latestAlbum: "American V"
// }


Friday, 17 October 2014

Tracking activities by public_activity in rails

In practice how ever you want to track all activities in the applications its pretty easy to do this by public_activity gem.here is small implementation of public activity.lets have a look:

To implement public_activity you have to follow these steps

1. Install gem:
install gem by running command 'gem install public_activity' or
write gem 'public_activity' in your gem file and do bundle install.
2. Generate/install migrations:
run command : rails g public_activity:migration
3. Migrate database: run rake db:migrate
4. Model configration:

write following code inside your model
include PublicActivity::Model
tracked
if you want to add owner(creator) of the activity then do this

-> write following code inside your ApplicationController
  include PublicActivity::StoreController
-> write following in your model:
include PublicActivity::Model
tracked ,owner: ->(controller, model) { controller && controller.current_user }

5. Skiping actions:
public activity create an record in PublicActivity::Activity on each create/update/destroy of the tracked model if you want to skip any action you can do like this:
include PublicActivity::Model
tracked ,except: [actions]
6.Creating custom activity:
if you want to create a custom activity you can do this:
resource.create_activity :action, owner: current_user

as public_activity track only models that's why if you want to log any other action that not reflect any changes to model then you have to create custom activities according to your requirements.




Friday, 19 September 2014

Working with Engines in Rails

Engines can be considered as a small applications that provide functionality to their host applications. A Rails application is actually just a "supercharged" engine, with the Rails::Application class inheriting a lot of its behavior from Rails::Engine.
Therefore, engines and applications can be thought of almost the same thing, just with subtle differences, as you'll see throughout this guide. Engines and applications also share a common structure.Engines are also closely related to plugins. The two share a common lib directory structure, and are both generated using the rails plugin new generator. The difference is that an engine is considered a "full plugin" by Rails (as indicated by the --full option that's passed to the generator command).. An engine can be a plugin, and a plugin can be an engine.
1). Getting help: For help regarding engine run the following command:
rails plugin --help
2).Generating an engine: To generate an engine, you will need to run the plugin generator and pass it options as appropriate to the need.run the following command in terminal:
rails plugin new engine_name --mountable
The --mountable option tells the generator that you want to create a "mountable" and namespace-isolated engine. This generator will provide the same skeleton structure as would the --full option, and will add: 
          Asset manifest files (application.js and application.css
          A namespaced ApplicationController stub 
          A namespaced ApplicationHelper stub
         A layout view template for the engine
         Namespace isolation to config/routes.rb  
Note: Don't forget to run bundle install command to install all dependencies.

Mountable engine is as like full rails application you can generate models,controller and do all the stuff what you do in a rails application.

3).Setup engine in rails app:
for install all migrations:

rake engine_name:install:migrations

If you have multiple engines then run:

rake railties:install:migrations

4).Running migration: if you have only one enigne then run

rake db:migrate

If you have multiple engines then run:

rake db:migrate SCOPE=engine_name

5).Using in application: 

a).Add following line in you application's gem file

gem 'engine_name' , path :'path_of_your_enigne'

path_of_your_enigne is the full path where your engine_name.gemspec is present.

b).Add this line in your routes.rb file:

mount engine_name::Engine => "/mount_name"

mount_name can be anything that you want to give to your engine's path usually it is the engine_name.


6).Communicating between rails app and engine:

a). if you want to access engine resource in your rails app then:
 
routes: engine_name.path_to_your_resource
Model: EngineName::ModelName
b). if you want to access main rails application from engine then:

routes: main_app.path_to_your_resource




 

Friday, 1 August 2014

Working with memcached in Ruby on Rails

Memcached is a general-purpose distributed memory caching system. It is often used to speed up dynamic database-driven websites by caching data and objects in RAM to reduce the number of times an external data source (such as a database or API) must be read.
Memcached is free and open-source software. Memcached runs on Unix-like (at least Linux and OS X) and on Microsoft Windows.

here is example to use in Ubuntu:

1.installation:  sudo apt-get install memcached
2.setup in rails:  gem install dalli
 (dalli is gem to use memcached in rails)
3.configure Rails: there are two ways to use memcached in rails:

a).Using Rails cache as memcached: 
 write following lines of code in :
config/environments/production.rb (development.rb,staging.rb) as per environment.
config.cache_store = :dalli_store
config.action_controller.perform_caching = true
 
b).Using system memcached: follow these steps
 
class MemCacheClass
 
def initialize
     @connection ||= Dalli::Client.new("#{host}:#{port}", compress: true) 
   // where host is host and port is the port on which memcached is running
 default is 11211.
end

  def get(key)
    @connection.get(key) // return the value for given key.
  end

  def set(key,value, time_stamp)        
    @connection.set(key, value, time_stamp)
  end
 end
 
Uses: you can get and values from memcached
 
Get Value : 
conn = MemCacheClass.new
conn.set(key,value,time) // set value of key to given value for given
time period
conn.get(key) // get value of given key.
  







Friday, 25 July 2014

Difference between clone and dup

clone: Produces a shallow(as deep as possible) copy of obj.the instance variables of obj are copied, but not the objects they reference. Copies the frozen(cant be modified more) state of obj.

clone will copy the object alone with its internal state. suppose obj extends any module then clone of the obj also have that module extended.

example:
class Hello 
end

 module SayHello
 
  def sayhello
     'hello'
   end
 end


 s = Hello.new
 s.extend(SayHello)
 s1 = s.clone
 s1.sayhello                //     returns  "hello"


dup: Produces a shallow copy of obj.the instance variables of obj are copied, but not the objects they reference.

example:

use the above example if we use dup to create a copy of obj then dup will create a shallow copy of the obj excluding the internal state of the obj.

 s = Hello.new
 s.extend(SayHello)
 s1 = s.dup
 s1.sayhello             
 //     returns  undefined method `sayhello' for #<Hello:0x0000000197b688>















Friday, 18 July 2014

Working with CSV in jquery(Papa parse)

Papa Parse is a powerful CSV (delimited text) parser that gracefully handles large files.you can easily use this and can parse large csv files efficiently.you can get papa parse here.

here is short example of using  Papa Parse:

1.Converts csv to json:
var result = Papa.parse(csv_file)


2.Parse local CSV files:

 $('input[type=file]').parse({
config: {
             complete: function(results) {
                  console.log("Parse results:", results.data);
                 }
             }
           });
 3.Parse remote CSV files:
Papa.parse("http://example.com/file_name.csv", {
        download: true,
        complete: function(results) {
                         console.log("Remote file parsed!", results);
                       }
       });
4.Get data keyed by field name:
var results = Papa.parse(csv, {
                          header: true
                          });        
 


Friday, 11 July 2014

Working with Action Mailer Callbacks in Rails

If you want to perform some operation after the mail delivery you can use the Action Mailer callbacks.

Action Mailer allows for you to specify a before_action, after_action and around_action
  • Filters can be specified with a block or a symbol to a method in the mailer class similar to controllers.
  • You could use a before_action to populate the mail object with defaults, delivery_method_options or insert default headers and attachments.
  • You could use an after_action to do similar setup as a before_action but using instance variables set in your mailer action.
 you can use callbacks same as like in the controllers.here is an example of it.

class UserMailer < ActionMailer::Base
  after_action :set_delivery_options

  def feedback_message(user)
    @user = user
    mail
  end
 
  private
 
    def set_delivery_options
      # You have access to the mail instance,
      # @user instance variables here
      # your code here
    end
end

Friday, 4 July 2014

Working with Nokogiri::XML::Node with Rails

I am using gem 'nokogiri' for Nokogiri::XML::Node manipulations.here are the some examples of performing the basics operations on the Nokogiri::XML::Node.
you can perform these operations with Nokogiri::XML::Node.

say for the example you have the Nokogiri::XML::Node named node,now here are some basic operation with this node.

1.Get parent: you can fetch the parent of the node by,
node.parent // will return the parent of the node.

2. Get xpath :
node.path // will return of the xpath of the node in document.
 

3.Get node at some path in document:
_node = doc.xpath('some_path')
where doc is a nokogiri document.it will return a nodeset if you want to get the exact node then do this

_node = doc.xpath('some_path')[0] or _node = doc.xpath('some_path').first

4.Get children:
node.children // will return the nodeset of childs of node your can select them according to your need.

5.Add children:
node.add_child('child_html') // add child in as the last child.

6.Add siblings:
node.add_next_sibling('some_html') // add a sibling node after the node in parent.
node.add_previous_sibling('some_html') // add a sibling node before the node in parent node.

7.Replace a node:
node.replace('replace_node's_html')// replace a node by given html.

8. Styling a node:
node['class'] = 'some_css_class' // add a css class to node.
css_class = node['class'] // get the css_class of the node.

9. Show html:
node.to_html // will return html of the node.

Friday, 27 June 2014

Comparing two html files using nokogiri

How ever in practice if you want to compare two html files and the output will be customized according to your requirement like you want to change color or add some extra html tags in the modified tags or add any class to the modified node,the awesome way to do it by using nokogiri. here is an example of doing this:

Example: In this example I am adding the <del> tag before the deleted or modified element and just add the newly added elements to the first html file.

1. install nokogiri and nokogiri-diff.
    (nokogiri provide the efficient way to modify and access the elements of the htmls)
2. require 'nokogiri/diff' in your code.
3. parsing html by nokogiri, you can read any html file and can parse by nikogiri to get the nokogiri doc for operations.I am just giving the small example by parsing a html string to the nikogiri.

_first_doc =  Nokogiri::HTML('<p>hello</p><p>this is demo example</p><p>byee</p>')

_second_doc =  Nokogiri::HTML('<p>hii</p><p>this is demo example</p><p> good byee</p>')

4. Get the difference:

 _first_doc.diff(_second_doc,:removed => true) do |change,node|
  node.replace("<del>#{node.to_html}</del>")
 end // adding <del> tag to modified elements(node).

 _first_doc.diff(_second_doc,:added => true) do |change,node|
  _parent = _first_doc.search(node.parent.path).first
  _parent.add_child(node)
 end // adding newly added elements in the result.

5.Get the output : now you can see the changes by printing  _first_doc.to_html

output will be like:

<html><body>
<del><p>hello</p></del>
<p>hiii</p> 
<p>this is demo example</p>
<del><p>byee</p></del>
<p>good byee</p>
</body></html>









Saturday, 21 June 2014

Three ways to do eager loading in Rails

There are three ways to do eager load in rails.they are:

1. includes
2. preload and
3. eager_load

includes delegates the job to preload or eager_load depending on the presence or absence of condition related to one of the preloaded table.

preload is using separate DB queries to get the data.

eager_load is using one big query with LEFT JOIN for each eager loaded table.

In Rails 4 you should use #references combined with includes if you have the additional condition for one of the eager loaded table.

  Typically, when you want to use the eager loading feature you would use the includes method, which Rails encouraged you to use since Rails2 or maybe even Rails1 ;). And that works like a charm doing 2 queries:
    
User.includes(:addresses)
#  SELECT "users".* FROM "users" 
#  SELECT "addresses".* FROM "addresses" WHERE "addresses"."user_id"
IN (1, 2)
doing one query. So what is #includes for? It decides for you which 
way it is going to be.
User.preload(:addresses)
#  SELECT "users".* FROM "users" 
#  SELECT "addresses".* FROM "addresses" WHERE "addresses"."user_id" 
IN (1, 2)
 Apparently #preload behave just like #includes.
If you use #preload, it means you always want separate queries. If 
you use #eager_load you arelet Rails handle that decision.What is
query conditions. Let's see an example where #includes delegates to 
#eager_load so that there is one big query only.the decision based
on, you might ask. It is based on

Friday, 30 May 2014

Understanding JavaScript:NaN



NaN,not a number, is a special value used to denote an unrepresentable value. With JavaScript, NaN can cause some confusion, starting from its typeof and all to the way the comparison is handled.

Several operations can lead to NaN as the result. Here are some examples:

Math.sqrt(-2)          //NaN

Math.log(-1)           //NaN

parseFloat('foo')    //NaN

0/0                          //NaN


The first trap is usually the unexpected result of calling typeof:

console.log(typeof NaN); // 'number'

In a way, while NaN isn’t supposed to be a number, its type is number. Got it?
Let’s compare two NaNs:

var x = Math.sqrt(-2);

var y = Math.log(-1);

console.log(x == y);         // false

Maybe that’s because we’re supposed to use strict equal (===) operator instead? Apparently not. 

var x = Math.sqrt(-2);

var y = Math.log(-1);

console.log(x === y); // false

even if we test like this:

console.log(x == x);       // false 

if we compare real NaNs then:

console.log(NaN === NaN); // false

Because there are many ways to represent a NaN, it makes sense that one NaN will not be equal to another NaN.


Friday, 23 May 2014

Using Named Scopes Across Models with ActiveRecord #Merge

If you want to use named scopes on joined models, then there are two ways to find the solution.


1. Define a named scope inside each model : you can define a different named scope in each model. lets have an example:

we have two models named user and project. these model have associations lke this,

class User < ActiveRecord::Base

  has_many :projects


end
 --------------------------------------------------------------------------------------------------------------------------------
class Project < ActiveRecord::Base

  belongs_to :user


  scope :available, -> {where(available: true)}
  scope :unavailable, -> {where(available: false)}



end

now if we to get the all projects that are available by the scope then we have to define a named scope inside the user model.

 scope :available_projects, -> {joins(:projects).where("projects.available = ?" ,true)}



2. Use Merge to use defined named scope in another model: 
Other way to use named scope just use merge in your query as like:

 User.joins(:projects).merge(Project.available)
User.joins(:projects).merge(Project.unavailable)








there is no need to have an extra named scope inside the user only one query can can do the same thing as the scope available_projects do.

Friday, 16 May 2014

JQuery: width() vs css('width') and height() vs css('height')

jQuery provides two ways to set width and height of any element. You can set using css or you can use jQuery provided methods.

 If you want to set the width or height of any DOM then

$('#div_1').css('width','100px');
$('#div_1').width(100); 


Then what is the difference?

The difference lies in datatype. As its clear in code that with width() method you need to append 'px' to the width value and with css('width') you don't need to specify.  


When you want to read width of any element then css('width') method will return you string value like '100px' while width() will return an integer value.

$('#div_1').css('width'); // will return '100px'


$('#div_1').width(100);  // will return 100

So if you want to do any kind of manipulation then width() function is the best option.


note: same with the height() and css('height') methods.

 


 

Saturday, 10 May 2014

Using pre-compiled assets in Rails Development Environment

 if you want to use the pre-compiled assets in Development Environment then follow these steps:

1. Edit development.rb : Add the following lines inside your config/environments/development.rb


  config.assets.debug = false
  # Disable Rails's static asset server (Apache or nginx will already do this).
  config.serve_static_assets = true

  # Compress JavaScripts and CSS.
  config.assets.js_compressor = :uglifier
  # config.assets.css_compressor = :sass

  # Do not fallback to assets pipeline if a precompiled asset is missed.
  config.assets.compile = false

  # Generate digests for assets URLs.
  config.assets.digest = true


if you want to compile your other assets like assets/your_dir/ style.css ,assets/your_dir/ custom.js etc then add the following line in your  config/environments/development.rb

 config.assets.precompile += %w( your_dir/style.css, your_dir/custom.js)




2. Compile your assets in Development Environment: compile your assets by the following command

rake assets:precompile RAILS_ENV=development

3. Restart your Rails server: Now restart your server and your application will serve compile assets in development environment.

Friday, 18 April 2014

Adding title to Rails view

You can add your title for views in two ways.for adding title in views you have to follow these steps:

1-> add <title><%= yield(:title) %></title> inside the header of your layout.
2-> now you can add your title inside your view.there are following ways to do that:

  a-> use this line in your view:
      <%= content_for(:title, "Title for specific page") %>

  b-> use helper method:
  •  add a helper method in application_helper

       def title(page_title)
            content_for :title, page_title.to_s
      end


  • inside your view:
           <%= title "your custom title" %>
  c-> if you want to write title for view in controller then add this method inside   your application_controller.

  def view_context
    super.tap do |view|
      view.content_for :title, "your title"
    end
  end


if you want to add title according to your controller and action names pair then:

  def view_context
    super.tap do |view|
      view.content_for :title, "#{controller_name}_#{action_name}"
    end
  end

 

Saturday, 12 April 2014

Converting Html to Pdf using wkhtmltopdf

wkhtmltopdf is open source (LGPL) command line tools to render HTML into PDF and various image formats using the QT Webkit rendering engine. These run entirely "headless" and do not require a display or display service.

wkhtmltopdf convert a html to pdf with all images and css.

1-Install wkhtmltopdf: download from link.
or
sudo apt-get install wkhtmltopdf  // in ubuntu.

2.Conversion: 
convert your html file to pdf by the following command:

wkhtmltopdf html_file_name.html pdf_name.pdf

this will create the pdf file named pdf_name.pdf inside the current directory.

Example:


 wkhtmltopdf www.yahoo.com yahoo.pdf

this command create a yahoo.pdf inside the current working directory and looks like same as html file.

 

Friday, 4 April 2014

JavaScript functions slice and splice

In JavaScript, mistaking slice for splice (or vice versa) is a common mistake. These two functions, although they have similar names, are doing two completely different things.

slice:Array’s slice is quite similar to String’s slice. According to the specification, slice needs to accept two arguments, start and end. It will return a new array containing the elements from the given start index up the one right before the specified end index. It’s not very difficult to understand what slice does:

Example:
'abcdefg' .slice(1,2)       // 'b'
'abcdefg' .slice(1,3)       // 'bc'
[1,2,3,4,5] .slice(1,2)     //  [2]
[1,2,3,4,5] .slice(1,3)     //  [2,3]


An important aspect of slice is that it does not change the array which invokes it. The following code fragment illustrates the behavior. As you can see, arr1 keeps its elements and arr2 gets the sliced version thereof.

var arr1 = [1,2,3,4,5];
var arr2 = arr1.slice(1, 2);
console.log(arr1);          // [1,2,3,4,5]
console.log(arr1);          // [2]




splice: Although splice also takes two arguments (at minimum), the meaning is very different:


[1,2,3,4,5] .splice(1,2)     //  [2, 3]



splice also mutates the array that calls it. This is not supposed to be a surprise, after all the name splice implies it.


var arr1 = [1,2,3,4,5];
var arr2 = arr1.splice(1, 2);
console.log(arr1);          //
[1, 4, 5]
 console.log(arr1);          // [2,3]


Thursday, 27 March 2014

Taking Picture from WebCam using Webcam jQuery plugin

WebcamJS is a small standalone JavaScript library for capturing still images from your computer's camera, and delivering them to you as JPEG or PNG. The images can then be displayed in your web page, rendered into a canvas, or submitted to your server.  WebcamJS uses [HTML5 getUserMedia], but provides an automatic and invisible Flash fallback.

WebcamJS is based on my old [JPEGCam] project, but has been redesigned for the modern web.  Instead of relying on Flash and only being able to submit images directly to a server, WebcamJS delivers your images as client-side Data URIs, and it uses HTML5 getUserMedia where available.  Flash is only used if your browser doesn't support getUserMedia, and the fallback is handled automatically.

Implementation:

1. Download webcam.js and put inside your application.download webcam.js click here.
2.include webcam.js in your html  file.
   <script src="webcam.js"></script>
3.configure your cam viewer setting:
   Webcam.set({
        width: 320,
// width of cam viewer 
        height: 240, // width of cam viewer
        image_format: 'jpeg', // image format
        jpeg_quality: 90       
// image quality
    });
4. Load your cam viewer:
Webcam.attach( '#web_cam' ); // inside script

5. take a picture:
function take_image() {
            // take snapshot and get image data
            var data_uri = Webcam.snap();
           
            // display results in page
            document.getElementById('results').innerHTML =
                '<h2>Here is your image:</h2>' +
                '<img src="'+data_uri+'"/>';
        }

call this take_image function to take picture from your cam.it will take an image and show it into the output's DOM.


 Html for the above example:
--------------------------------------
<div id="results"></div>    
<div id="web_cam" ></div>
<form>
        <input type=button value="Take Photo" onClick="take_image()">
</form>










   

Thursday, 6 March 2014

Using FlashLight plugin in Phonegap Applications

Flashlight works with PhoneGap applications,Compatible with PhoneGap 3.0.0 and up. You can implement the plugin with these simple steps.

1. Installation:
  a. Download phonegap flashlight plugin here.
  b. place FlashLight.js inside your application's www/js/plugin folder.
  c. Add the following xml to your config.xml to always use the latest version of  this plugin:

  <gap:plugin name="nl.x-services.plugins.flashlight" />

  or to use this exact version:

  <gap:plugin name="nl.x-services.plugins.slashlight" version="1.0" />

 d. Reference the JavaScript code in your index.html:

 <script src="js/plugins/Flashlight.js"></script>

Note: keep it mind that FlashLight plugin must be referenced after phonegap in your index.html file.

2. Usage:
use these scripts to handle FlashLight events.

 window.plugins.flashlight.switchOn(); // to on flashlight.
 window.plugins.flashlight.switchOff(); // to off flashlight.

As an alternative to switchOn and switchOff, you can use the toggle function

window.plugins.flashlight.toggle();




Thursday, 20 February 2014

Signing Phonegap's Android Applications and Deploying on Google Play

The Android system requires that all installed applications be digitally signed with a certificate whose private key is held by the application's developer.

before submit release on google play your application must be build in release mode.


Signing in Release Mode:

When your application is ready for release to other users, you must:

    1-Obtain a suitable private key
    2-Compile the application in release mode
    3-Sign your application with your private key
  
Generating private Key:

 To generate a self-signed key with Keytool.Keytool is java tool for generating private key. use following command to generate private key for signing your android application:

keytool -genkey -v -keystore app_signing.keystore -alias <alias_name> -keyalg <alg> -keysize <size> -validity 10000

where:

-genkey : Generate a key pair (public and private keys).

-v          : Enable verbose output.

app_signing: name of your key_file.

-alias    :  An alias for the key. Only the first 8 characters of the alias are used.

-keyalg <alg>:    The encryption algorithm to use when generating the key. Both DSA and RSA are supported.




 -keysize <size>:    The size of each generated key (bits). If not supplied, Keytool uses a default key size of 1024 bits. In general, we recommend using a key size of 2048 bits or higher.

-validity <valdays> :  The validity period for the key, in days.A value of 10000 or greater is recommended.

==================================================

Note: during creation of private key system ask for storeKey password,give any password and remember that password.it will required when you build the application in release mode.




----------------------------------------------------------------------------------------------------------------------------------
Building application for release:
1- after creating the signing key you have to add the key.keystore  file in your profile on https://build.phonegap.com/.
 
2- upload application.zip folder(compressed file of your application's www folder).

3- unlock your private key by your storekey password.

4- build your application.

--------------------------------------------------------------------------------------------------------------------------------

if you download your build app.apk from https://build.phonegap.com/
you can see that it is a app-release.apk.this build is signed build and you can just upload it on google play.


















Thursday, 30 January 2014

JavaScript best practices

1 – Don’t forget var keyword when assigning a variable’s value for the first time.
      Assignment to an undeclared variable automatically results in a global variable being created. Avoid global variables.
2- Use strings accumulator-style: Using + operator a new string is created in memory and the concatenated value is assigned to it. Only after this the result is assigned to a variable.
Example:

a='A'+'B';   // slower

Faster :
a+='A';
a+='B';

3- Primitive operations can be faster than function calls: Consider using alternative primitive operation over function calls in performance critical loops and functions.

Slow:
var min = Math.min(a, b);
arr.push(val);

Faster:
var min = a < b ? a : b;
arr[arr.length] = val;

4-Maximize object resolution speed and minimize scope chain:
Inefficient way:
var url = location.href;

Efficient one:
var url = window.location.href;

5-use === instead of == : The == (or !=) operator performs an automatic type conversion if needed. The === (or !==) operator will not perform any conversion. It compares the value and the type, which could be considered faster than ==.

[10] === 10    // is false
[10]  == 10    // is true
'10' == 10     // is true
'10' === 10    // is false


6-Use Semicolons for line termination: It is a best practice to use semi-colons for line termination.You won’t be warned if you forget it, because in most cases it will be inserted by the JavaScript parser.

7- Create a Self-calling Function: 
(function(){
    // some private code that will be executed automatically
})(); 

(function(a,b){
    var result = a+b;
    return result;
})(10,20)

this function is self called function and the code will execute automatically.

8-Get a random number in a specific range:

var x = Math.floor(Math.random() * (max - min + 1)) + min;

9-Generate an array of numbers with numbers from 0 to maxvar numbersArray = [] , max = 100;

10-Append an array to another array:
var arr = [1 , "foo" , {name "Joe"} , -28];

var arr2 = ["Dog" , 5 , 100];
Array.prototype.push.apply(arr, arr2);
/* array1 will be equal to  [1 , "foo" , {name "Joe"} , -28 , "Dog" , 5 , 100] */

11-Verify that a given argument is a number:

function isNumber(n){
    return !isNaN(parseFloat(n)) && isFinite(n);
}

12-Verify that a given argument is an array:

Array.isArray(obj);

13-Get the max or the min in an array of numbers:

var  numbers = [5, 4 , 12 , -21 , 28 , 400 , 122205, -8511];
var maximum = Math.max.apply(Math, numbers); // 122205
var minimum = Math.min.apply(Math, numbers);  // -8511

14-Empty an array:
var myArray = [13 , 22 , 100 ]; 
myArray.length = 0; // myArray will be equal to [].

15-Don’t use delete to remove an item from array: Use splice instead of using delete to delete an item from an array. Using delete replaces the item with undefined instead of the removing it from the array.

16-Truncate an array using length:
var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ]; 
myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].

if you set the array length to a higher value, the length will be changed and new items will be added with undefined as a value. The array length is not a read only property.

myArray.length = 10; // the new array length is 10
myArray[myArray.length - 1] ; // undefined

17-Use the map() function method to loop through an array’s items:
var squares = [1,2,3,4].map(function (val) { 
    return val * val; 
});
// squares will be equal to [1, 4, 9, 16]

18-Rounding number to N decimal place:

var num =2.443242342;
num = num.toFixed(4);  // num will be equal to 2.4432

NOTE : the toFixed() function returns a string and not a number.

19-Floating point problems:
0.1 + 0.2 === 0.3 // is false

Why does this happen? 0.1 +0.2 is equal to 0.30000000000000004. What you need to know is that all JavaScript numbers are floating points represented internally in 64 bit.

20-Avoid negative indexes in arrays:
var numbersArray = [1,2,3,4,5];
var from = numbersArray.indexOf("foo") ;  // from is equal to -1
numbersArray.splice(from,2);    // will return [5]

if we using splice method with negative index then it will delete last element from the array.

21-Pass functions, not strings, to setTimeout() and setInterval():
If you pass a string into setTimeout() or setInterval(), the string will be evaluated the same way as with eval, which is slow.

Instead of using…

setInterval('doSomethingPeriodically()', 1000); 
setTimeout('doSomethingAfterFiveSeconds()', 5000);

…use…

setInterval(doSomethingPeriodically, 1000); 
setTimeout(doSomethingAfterFiveSeconds, 5000);



for more detail  Click Here





Thursday, 23 January 2014

Techniques to Increase Performance of PhoneGap Applications

1-> Dont create the UI on server.
     Dont create UI on server,it makes the application slow.

2-> Dont wait for the data to display UI.
    Dont wait for data to display UI.display UI first and then update data.

3-> Cache Everything
     cache everything as much you can and display the existing data first in UI then update the UI by the updated data.don't wait for updated data to display all data in UI.but caching much is also make application slow.

3-> avoid click event
     Click event is very slow as compare to touchStart event. so use touchStart in place of click.

4-> Optimize image.
5-> Limit shadow and gradients.
6-> minimize browser re-flows.

Thursday, 16 January 2014

How to Build and Test Blackberry Phonegap application on simulator in Windows

Cordova for BlackBerry makes use of the BlackBerry WebWorks framework. BlackBerry WebWorks tooling is available for Windows or Mac environments.

WebWorks applications can ONLY be deployed to the following BlackBerry platforms:

BlackBerry OS 5.0 and higher
BlackBerry PlayBook
BlackBerry 10 (QNX)

============================

Requirements
============================
windows 64 or 32 bit
Java Development Kit (JDK)(32 bit)
Apache Ant
Windows: Apache Ant.

=========================
Install sdk for the above
=========================
[BlackBerry 10 (QNX) SDK] (https://developer.blackberry.com/html5/download/#blackberry10)
[BlackBerry PlayBook SDK] (https://developer.blackberry.com/html5/download/#playbook) & Adobe Air SDK
[BlackBerry Smartphones SDK] (https://developer.blackberry.com/html5/download/#smartphones)

=========================
Install simulators
=========================
install simulators for the apropriate version

for blackberry 10 and playbook adobe air sdk require before installation and VMplayer is required to run the simulators.

=========================
Register for Signing Keys
=========================
for registering signing key Click Here

========================
Install Cordova
========================
1- npm install -g phonegap

2-  npm install cordova

====================

Edit the project property file
===========================
blackberry.bbwp.dir=
playbook.bbwp.dir=
qnx.bbwp.dir=

to 

blackberry.bbwp.dir=C:\\Program Files (x86)\\Research In Motion\\BlackBerry WebWorks SDK 2.3.1.5
playbook.bbwp.dir=C:\\Program Files (x86)\\Research In Motion\\BlackBerry WebWorks SDK for TabletOS 2.2.0.5\\bbwp
qnx.bbwp.dir=C:\\Program Files (x86)\\Research In Motion\\BlackBerry 10 WebWorks SDK 1.0.4.11

=========================



Build project
====================
go to project directory and build by following command

ant qnx buil // for blackberry 10
ant playbook build // for playbook
ant blackberry build // for blackberry smartphones





If error loading jvm.dll occurs then set java path to  C:\Program Files (x86)\Research In Motion\BlackBerry WebWorks SDK for TabletOS 2.2.0.5\jre\bin

===================
load to simulator
==================

ant qnx load-simulator
ant playbook load-simulator
ant blackberry load-simulator 

for qnx and playbook simulators must be enable/on before the load-simulator command.

Thursday, 9 January 2014

Why we use ActiveSupport::Concern

The Concern provides a mechanism for composing modules.Concerns are pieces of code that allow you to better organize the code that you write. This feature has actually been around for a long time prior to Rails 4, Rails 4 merely creates the folders for you and sets up the environment.

Included
==================================================
Module defines the callback included which is called when a module is included into another class or module.  For example see the following code:
==================================================

module Named
  def self.included(base)
    base.validates_presence_of :first_name, :last_name
  end

  def full_name
    "#{first_name} #{last_name}"
  end
end

..........................
class Person
  include Named
end



When Person includes Named, the included method is called on Named with a reference to Person. Now, what if you want a module that builds upon Named?
=================================================

module Mailable
  include Named

  def self.included(base)
    email_regexp = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/
    base.validates_format_of :email, with: email_regexp
  end

  def send_greeting
    mail = WelcomeMailer.greet(email, first_name, last_name)
    mail.deliver
  end
end

.................................................................................................................................
if we do
require 'mailable'

then it will gives
# => NoMethodError: undefined method `validates_presence_of' for Mailable:Module

This will fail when Named is included into Mailable. The Name.included callback will be executed with Mailable as the base, but Mailable doesn't define validates_presence_of:

==================================================

We really want these modules to wait until they are included in your model before the included callback is invoked. Concern works around this issue for us:

module Named
  extend ActiveSupport::Concern

  included do
    base.validates_presence_of :first_name, :last_name
  end 
end

module Mailable
  extend ActiveSupport::Concern
  include Named

  included do
    email_regexp = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/
    base.validates_format_of :email, with: email_regexp
  end
end

First a module extends Concern, and then instead of defining def self.included it calls included with a block. Concern delays calling these blocks until your module is included in something that is not a Concern.