Import and Export using Roo gem

Import and Export using Roo gem:-

Controller:-

class IncidentsController < ApplicationController

layout ‘incident_layout’

def index

@incident = Incident.all

# respond_to do |format|

# format.html

# format.csv {render text: @incident.to_csv}

# end

end

def import

if(params[:file].present?)

Incident.import(params[:file], current_company)

redirect_to incidents_path

end

end

def export

begin

file_to_download = “sample_incident.csv”

send_file Rails.public_path + file_to_download, :type => ‘text/csv; charset=iso-8859-1; header=present’, :disposition => “attachment; filename=#{file_to_download}”, :stream => true, :buffer_size => 4096

rescue

redirect_to new_incident_path

end

end

# def import

# Incident.import(params[:file])

# redirect_to incidents_path

# end

def new

@incident = Incident.new

end

def edit

@incident = Incident.find(params[:id])

incident_initializers( @incident.department_id, @incident.team_id, @incident.request_type_id, @incident.incident_category_id, @incident.sub_category_id, @incident.incident_status_id, @incident.resolution_id)

end

def create

@incident = Incident.create(incident_params)

@incident.set_incident_status(@incident, params[:commit])

if @incident.save

flash[:notice] = “The incident was successfully created”

redirect_to incidents_path

else

redirect_to new_incident_path

end

end

def update

@incident = Incident.find(params[:id])

@incident.set_incident_status(@incident, params[:commit]) if params[:commit] == “Initiate incident”

if @incident.update_attributes(incident_params)

redirect_to edit_incident_path

else

incident_initializers( @incident.department_id, @incident.team_id, @incident.request_type_id,@incident.incident_status_id,@incident.sub_category_id,@incident.resolution_id)

render ‘edit’

end

end

def incident_all

if params[:stage].present?

@incidents = current_user.incidents_stage(params)

else

@incidents = current_user.accessible_incidents

end

end

def download_incident_document

attachment = Attachment.find(params[:id])

send_file(Rails.public_path.to_s + attachment.attachment_file_url)

end

def download_resolution_document

attachment = Attachment.find(params[:id])

send_file(Rails.public_path.to_s + attachment.attachment_file_url)

end

def remove_attachment

attachment = Attachment.find(params[:id])

attachment.delete

end

def show

@incident = Incident.find(params[:id])

# @incident=Evaluate.find(params[:id])

respond_to do |format|

format.html

format.pdf do

@pdf = (render_to_string pdf: “PDF”, template: “incidents/show.pdf.erb”, layout: ‘layouts/pdf.html.erb’, encoding: “UTF-8”)

send_data(@pdf, type: “application/pdf”, filename: @incident.title)

end

end

end

def incident_dashboard

@incident = Incident.all

@inci= Incident.find_by_sql(“SELECT count(*) FROM incidents “)

@category_1= Incident.find_by_sql(“SELECT count(*) FROM incidents where incident_category_id=1”)

@category_2= Incident.find_by_sql(“SELECT count(*) FROM incidents where incident_category_id=2”)

@category_3= Incident.find_by_sql(“SELECT count(*) FROM incidents where incident_category_id=3”)

@category_4= Incident.find_by_sql(“SELECT count(*) FROM incidents where incident_category_id=4”)

@category_5= Incident.find_by_sql(“SELECT count(*) FROM incidents where incident_category_id=5”)

@category_6= Incident.find_by_sql(“SELECT count(*) FROM incidents where incident_category_id=6”)

@category_7= Incident.find_by_sql(“SELECT count(*) FROM incidents where incident_category_id=7”)

@category_8= Incident.find_by_sql(“SELECT count(*) FROM incidents where incident_category_id=8”)

@priority_1= Incident.find_by_sql(“select count(*) from evaluates where incident_priority_id=1”)

@priority_2= Incident.find_by_sql(“select count(*) from evaluates where incident_priority_id=2”)

@priority_3= Incident.find_by_sql(“select count(*) from evaluates where incident_priority_id=3”)

# @inci= Incident.find_by_sql(“SELECT count(*) FROM incidents where date_trunc(‘month’, created_at), date_trunc(‘month’, created_at)+’1month’::interval-‘1day’::interval”)

# @inci= Incident.find_by_sql(“SELECT count(*) FROM incidents GROUB_BY created_at “)

end

private

def incident_params

params.require(:incident).permit(:Jobtitle, :title, :request_type_id, :incident_category_id, :sub_category_id, :date_occured, :summary,:department_id, :team_id, :incident_status_id, :comment, :contact_no, attachment_attributes: [:id, :attachment_file, :company_id])

end

def incident_initializers(department_id = nil, team_id = nil,incident_status_id = nil, incident_category_id = nil,sub_category_id = nil, request_type_id = nil,resolution_id = nil )

#@compliance_libraries = ComplianceLibrary.for_id_and_leaf(compliance_id) if compliance_id

#@departments = Department.for_location(location_id) if location_id

# section = Section.by_name(‘risk’).first

#@teams = Team.for_department_and_company(department_id, current_company.id, section.id) if department_id

#@team_users = Team.for_id(team_id).first.users << current_company.company_admin if team_id

end

end

Model:-

class Incident < ActiveRecord::Base

require ‘csv’

def self.open_spreadsheet(file)

case File.extname(file.original_filename)

when ‘.csv’ then Roo::CSV.new(file.path)

when ‘.xlsx’ then Roo::Excelx.new(file.path)

else raise “Unknown file type: #{file.original_filename}”

end

end

def self.import(file, company)

spreadsheet = Incident.open_spreadsheet(file)

start = 2

(start..spreadsheet.last_row).each do |i|

row_data = spreadsheet.row(i)

incident = Incident.new(:Jobtitle => row_data[0], :title => row_data[1], :request_type_id => row_data[2], :incident_category_id => row_data[3], :sub_category_id => row_data[4], :date_occured => row_data[5], :summary => row_data[6], :department_id => row_data[7], :team_id => row_data[8], :incident_status_id => row_data[9], :comment => row_data[10], :contact_no => row_data[11], :resolution_id => row_data[12],:incident_status_id => IncidentStatus.where(:name=>”New”).first.id)

incident.save(:validate => false)

end

end

# def self.to_csv

# CSV.generate do |csv|

# csv << column_names

# all.each do |company|

# csv << company.attributes.values_at(*column_names)

# end

# end

# end

belongs_to :request_type

belongs_to :incident_category

belongs_to :sub_category

belongs_to :department

belongs_to :team

has_one :evaluate

has_one :resolution

has_one :close

belongs_to :incident_status

has_one :attachment, as: :attachable

# validates :Jobtitle, presence:true, length: { in: 0..50 }

# validates :Jobtitle, uniqueness:true

#validates_form_of :title, :with =>/A(?=.*[a-z])[a-zds]+Z/i, :if => Proc.new{ |f| !f.title.blank? }

# validates :title, length: { maximum: 250 }, :if => Proc.new{|f| !f.title.blank? }

# validates :request_type_id, presence:true

# validates :incident_category_id, presence:true

# validates :sub_category_id, presence:true

# validates :date_occured, presence:true

# validates :summary, length: { maximum: 250 }, :if => Proc.new{|f| !f.summary.blank? }

# validates :department_id, presence:true

# validates :incident_status_id, presence:true

# validates :comment, length: { maximum: 250 }, :if => Proc.new{|f| !f.comment.blank? }

# validates_numericality_of :contact_no, :if => Proc.new{|f| !f.contact_no.blank? }

# validates :contact_no, length: { is: 10},:if => Proc.new{|f| !f.contact_no.blank? }

# validates :team_id, presence:true

accepts_nested_attributes_for :evaluate

accepts_nested_attributes_for :resolution

accepts_nested_attributes_for :close

accepts_nested_attributes_for :attachment, reject_if: lambda { |a| a[:attachment_file].blank? }

delegate :name, :to => :team, prefix: true, allow_nil: true

delegate :name, :to => :department, prefix: true, allow_nil: true

delegate :name, :to => :sub_category, prefix: true, allow_nil: true

delegate :name, :to => :incident_category, prefix: true, allow_nil: true

delegate :name, :to => :incident_status, prefix: true, allow_nil: true

delegate :name, :to => :incident_impact, prefix: true, allow_nil: true

delegate :name, :to => :request_type, prefix: true, allow_nil: true

def set_incident_status(incident, commit_name)

incident.incident_status_id = ((commit_name == “Save as Draft”) ? IncidentStatus.for_name(“Draft”).first.id : IncidentStatus.for_name(“New”).first.id)

return incident

end

end

#audit = Incident.new(:Jobtitle => row_data[0], :title => row_data[1], :request_type_id => row_data[2], :incident_category_id => row_data[3], :sub_category_id => row_data[4], :date_occured => row_data[5], :summary => row_data[6], :department_id => row_data[7], :team_id => row_data[8], :incident_status_id => row_data[9], :comment => row_data[10], :contact_no => row_data[11], :resolution_id => row_data[12])

View:-

<link href=”/assets/bootstrap-multiselect.css” rel=”stylesheet” />

<div class=”content”>

<div class=”container”>

<div class=”clearfix”> <a class=”import-btn” data-toggle=”modal” href=”#add_csv” style=”width:157px”><i class=”download-icons”></i>Import Incident</a>

</div> <!– <div class=”upload-btn clearfix”><a class=”grey_btn” href=”#add_csv” data-toggle=”modal”>Import audit from CSV</a></div> –>

<div class=”row”>

<% flash[:notice] if flash[:notice].present? %>

<div class=”form-group clearfix addissue”>

<div class=”modal fade” id=”add_csv”>

<div class=”modal-dialog modal-dialog_large”>

<div class=”modal-content”>

<div class=”modal-header”>

<button aria-hidden=”true” data-dismiss=”modal” class=”close” type=”button”> &nbsp; </button>

<h4 id=”myModalLabel” class=”modal-title”>Upload files only CSV</h4>

<div class=”modal-content-inner”>

<%= form_tag import_incidents_path, multipart: true do %>

<%= file_field_tag :file %>

<br>

<div class=”model-footer”>

<%= submit_tag “Import” ,:class => “black_btn” %>

<%= button_tag “Cancel”, type: ‘button’, “data-dismiss” => “modal”, :class => “orange_btn” %></div>

<% end %>

</div>

<p></p>

<p>

<%= link_to “Download Sample Incident CSV”, export_incidents_path(format: “csv”) %>

</p>

</div>

</div>

</div>

</div>

</div>

</div>

<div class=”page-wrap”>

<div class=”content”>

<div class=”container”>

<div class=”row”>

<div id=”example” class=”k-content”>

<div class=”risk-title”>Document a New Incident</div>

<%= form_for(@incident) do |f| %>

<%= render ‘form’,:f => f, :incident => @incident %>

<%= f.submit “Add Incident” %>

<%end%>

</div>

</div>

</div>

</div>

</div>

</div>

</div>

</div>

Advertisements

Active-Admin Documentation

Active-Admin Documentation:-

ActiveAdmin.register Author, :as => “Article” do # we can change the resource name

menu :label => “My Posts”, :priority=>1 #we can change the resouce name in the menus and priority used to arrange menus

#Disable the comment textarea

ActiveAdmin.setup do |config|

config.allow_comments = false

end

active_admin_importable

sidebar ‘Books by this Author’, :only => :show do

table_for Book.joins(:author).where(:author_id => author.id) do |t|

t.column(“Title”) { |book| book.name }

end

end

#Display items in the list

index do

column :id

column :first_name

column :last_name

#It will show the edit,delete,update option to every row

actions

end

show do

h6 post.first_name

div do

simple_format post.last_name

end

end

#Here we speifying the columnname to download in the CSV

csv do

column :first_name

column :last_name

end

# See permitted parameters documentation:

# https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters

#without permit params we cant edit,update,and delete.

permit_params :list, :of, :attributes, :on, :model

#

# or

#

# permit_params do

# permitted = [:permitted, :attributes]

# permitted << :other if resource.something?

# permitted

# end

#filter :first_name, :as => :check_boxes, :collection => proc { Author.all }

# filter :last_name, :as => :check_boxes, :collection => proc { Author.all }

#In the Search menu we have to specify the fields to search

#filter :first_name

#filter :last_name

#Disable the filter option

config.filters = false

#Order

config.sort_order = “id_asc”

#We can specify number of items to be display

config.per_page=5

#config.paginate = false (It will hide the next,last,preview)

ActiveAdmin.setup do |config|

# Disable entirely

config.download_links = false

# Want PDF added to default download links

config.download_links = [:csv, :xml, :json, :pdf]

end

end

wkhtmltopdf generation

wkhtmltopdf generation:-

Step-01:-

First you have to do some basic cofiguration for wkhtmltopdf generation in your system, so that open terminal and copy&paste the given commands

1. sudo apt-get install openssl build-essential xorg libssl-dev

or

sudo aptitude install openssl build-essential xorg libssl-dev
2. wget http://wkhtmltopdf.googlecode.wkhtmltopdf-0.9.2-

3. tar xvjf wkhtmltopdf-0.9.2-static-

4. chown root:root wkhtmltopdf-amd64

5. mv wkhtmltopdf-amd64 /usr/bin/wkhtmltopdf
6. which wkhtmltopdf (this command will generate path like “/home/selva/.rvm/gems/ruby-2.1.1/bin/wkhtmltopdf”)

Step-02:-

1. Open or create file name

config/initializers/wicked_pdf.rb and copy&paste the given code

WickedPdf.config = {

:exe_path => ‘/home/selva/.rvm/gems/ruby-2.1.1/bin/wkhtmltopdf’ (path of wkhtmltopdf)

}

Step-03:-

1. Open or create file name

app/views/layouts/pdf.html.erb and copy&paste the given code

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″ />

<%= wicked_pdf_stylesheet_link_tag “pdf” -%>

<%= wicked_pdf_javascript_include_tag “number_pages” %>

</head>

<body onload=’number_pages’>

<div id=”content”>

<%= yield %>

</div>

</body>

</html>

Step-04:-

1. Open or create file name

app/controllers/incidents_controller.rb

Inside the file you have to create method called “show”

def show

@incident = Incident.find(params[:id])

respond_to do |format|

format.html

format.pdf do

@pdf = (render_to_string pdf: “PDF”, template: “incidents/show.pdf.erb”, layout: ‘layouts/pdf.html.erb’, encoding: “UTF-8”) =>(Here you have to mention two file name are show.pdf.erb and pdf.html.erb)

send_data(@pdf, type: “application/pdf”, filename: @incident.title) =>(name of the download pdf file like @controller.field_name)

end

end

end

Step-05:-

1. Open or create file name

app/views/incidents/show.pdf.erb and inside the file you have to write your own format of pdf

<div class=”cls”></div>

<div class=”leftside”>

<label>Urgency: </label>

<div class=”content-wrap”>

<div class=”label_content”><%=@incident.name if @incident.name.present?%>(@controller_object.field_name if present it will generate report)</div>

</div>

<div class=”cls”></div>

<div class=”content-wrap”>

<label>Assignee</label>

<div class=”label_content”> <%=@incident.evaluate.assignee if @incident.evaluate.present?%></div>

</div>

<div class=”cls”></div>

<div class=”content-wrap”>

<label> TargetDate : </label>

<div class=”label_content”><%=@incident.evaluate.target_date if @incident.evaluate.present?%></div>

</div>

<div class=”cls”></div>

How to fetch dropdown values from model and show it in to view file

How to fetch dropdown values from model and show it in to view file

1. Open or create file in app/views/controller_name/view_file_name(like _form.html.erb)

Before going to code, i will explain the scenario. I have one model(Sla) or table(slas) in that table having some fields are id,name,minutes,hous,days but i am using those data in evaluate_controller on view file.

<div class=”form-group clearfix”>

<label class=”col-sm-5″><b>SLA :</b> </label>

<div class=”col-sm-7″>

<div class=”risk-select”>

<%= evaluate(evaluate_table object).select(:sla_id, options_for_select(Sla.all.collect {|s| [ s.name, s.id,{“days” => s.days},{“hours” => s.hours},{“minutes” => s.minutes}]}) =>(passing params) , {}, :onChange=> “time_difference()”) =>(Calling javascript method if change value or select values in dropdown) %>

<%#= evaluate.collection_select(:sla_id, Sla.all, :id, :name, {data: { behavior: ‘category_dropdown’ }})%>

</div>

</div>

2. Create a div tag for displaying value

<div id=”time_update_here”></div>

3. Define the javascript method

Note:-

<selectid=”incident_evaluate_attributes_sla_id”=>(Name of the select tag and it will show when seeing “firebug”) onchange=”time_difference()” name=”incident[evaluate_attributes][sla_id]”>

<script type=”text/javascript”>

function time_difference()

{

var ids=$(“#incident_evaluate_attributes_sla_id” =>(Name of the select tag) ).val() =>(It will get the id of selected item in dropdown)

var names=$( “#incident_evaluate_attributes_sla_id option:selected” ).text(); =>(It will get the name of selected item in dropdown)

var ms=$( “#incident_evaluate_attributes_sla_id option:selected” ).attr(“minutes” =>(field_name in sla table) ); =>(It will get the minutes of selected item in dropdown)

var hr= $( “#incident_evaluate_attributes_sla_id option:selected” ).attr(“hours”);

var ds=$( “#incident_evaluate_attributes_sla_id option:selected” ).attr(“days”);

var x = new Date();

var h = x.getHours();

var m = x.getMinutes();

var s = x.getSeconds();

var d = x.getDate();

if(h>hr)

{

//var hh=h-hr;

var hh=parseInt(h, 10) + parseInt(hr, 10);

}

else

{

//var hh=hr-h;

var hh=parseInt(hr, 10) + parseInt(h, 10);

}

if(m>ms)

{

//var mm=m-ms;

var mm=parseInt(m, 10) + parseInt(ms, 10);

}

else

{

//var mm=ms-m;

var mm=parseInt(ms, 10) + parseInt(m, 10);

}

if(d>ds)

{

var dd=parseInt(d, 10) + parseInt(ds, 10);

}

var t = “Target-Time:”+dd+”days”+hh+”hrs”+mm+”minutes”;

// var today = new Date();

// var birthday = new Date(“December 17, 1995 03:24:00”);

// var birthday = new Date(“1995-12-17T03:24:00”);

// var birthday = new Date(1995,11,17);

// var birthday = new Date(1995,11,17,3,24,0);

// document.write(names)

$(“#time_update_here” =>(Name of the div tag) ).html(t);

// alert(t);

}

</script>>

modified: vendor error during git status

1. Whenever you doing “git status” it will thrown some error like

modified: vendor/active_admin/lib/active_admin/views/pages/base.rb
modified: vendor/active_admin/lib/active_admin/views/pages/form.rb
modified: vendor/active_admin/lib/active_admin/views/pages/index.rb
modified: vendor/active_admin/lib/active_admin/views/pages/layout.rb
modified: vendor/active_admin/lib/active_admin/views/pages/page.rb

.

.

.

.
modified: vendor/active_admin/lib/active_admin/views/pages/show.rb
modified: vendor/active_admin/lib/active_admin/views/tabbed_navigation.rb
modified: vendor/active_admin/lib/active_admin/views/title_bar.rb

2. So that you have to change file mode to false and copy & paste given command in terminal

git config core.filemode false

3.Now you can try git status it will show now only modified file and new file.

 

 

How to enable hibernate mode in ubuntu14.04

How to enable hibernate mode in ubuntu :-

1.Open the terminal and copy & paste the given line in terminal
sudo vim /etc/polkit-1/localauthority/50-local.d/com.ubuntu.enable-hibernate.pkla
2.After copy and paste the given paragraph in the opened file
[Re-enable hibernate by default in upower]
Identity=unix-user:*
Action=org.freedesktop.upower.hibernate
ResultActive=yes

[Re-enable hibernate by default in logind]
Identity=unix-user:*
Action=org.freedesktop.login1.hibernate
ResultActive=yes
3.Copy and paste given command in terminal
killall indicator-session-service
4.Now Hibernaate mode will be enable
OR
When ever you want you want to put system mode just type the following command everytime
$ sudo pm-hibernate