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.