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>