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