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.