Friday, 6 February 2015

Templating in Rails by using .docx and unoconv

In practice we often use to convert docx files in several forms as like PDF and doc file by using unoconv utility in Ubuntu.

There is a general issue with  converting docx files having image in that file i.e image background will be change.while converting docx file to doc unoconv change image property. if you set image background to no fill in docx then it will be 'white background' in doc file.


To resolve this issue you can do the following steps:
1. Extract .docx file and go to 'test_docx_files/word/media' folder.
2. Put your image inside  'test_docx_files/word/media' folder.
3. Convert your image to '.emf' file and rename to to 'image1.emf'.
4. Come to  'test_docx_files' and run following command:

`zip -r ../hest1.docx .`

this will create a .docx file named 'test1.docx' outside of the 'test_docx_files' folder.
5. convert this .docx file to .doc file.

Now you can see your image is having same property as like in .docx file.

Friday, 30 January 2015

Export Data to csv/xls in Rails by using to_xls-rails gem

How ever in practice we require to export data in several forms like 'csv' and 'xls'.Its very easy to export data in csv or xls format in rails application.

Here an example of exporting data:

1. write gem 'to_xls-rails' and run `bundle install`.
2. write following code in controller:

 respond_to do |format|
    format.html # don't forget if you pass html
    format.xls {
    filename = "Posts-#{Time.now.strftime("%Y%m%d%H%M%S")}.xls"
    send_data(@posts.to_xls, :type => "text/xls; charset=utf-8; header=present", :filename => filename)
     }
  end

3. In your view write following code:

<%= link_to 'Excel Download', posts_path(:format => :xls) %>

4. Specify mime type inside the mime_type.rb:

Mime::Type.register "application/xls", :xls



enjoy!!

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.