Customize the event calendar for holiday, halfday and fullday

Event calendar is a way to show multiple, overlapping events across calendar days and rows. This is an interface to add events, edit events, & destroy event.

I just cramped while implemented the halfday and fullday functionality in event caledar. I think it will help you.

Generate the JSON for the holiday, event day count and event status(half or full)

below are the snippets of code of controller

def index
	if request.xhr?
		@events = Event.order("created_at desc")
		events = []  
		holiday = []
	   @holiday = HolidayList.all
		@events.each do |event|
		  events << {:id => event.id, :title => event.user.name + "   ( " + event.event_type.option + " )     "  ,:day_count => (event.days/0.5).to_s , :half=> ((event.days % 1) != 0) ? 1 : 0, :tip => "Type:" + event.event_type.option + " Resson:" +  event.reason || "",  :color=> event.event_type.color, :className=>"test",:description => event.reason || "Some cool description here...", :start => "#{event.from_date.iso8601}", :end => "#{event.to_date.iso8601}"}
		end
		@holiday.each do |hol|
		  events << {:id => hol.id, :title => hol.name + "   ( HOLIDAY )", :day_count => 1 ,:tip => "Type:Holiday  Resson:" +  hol.name || "", :half=> 0, :color=> "#B6B6B6", :className=>"holi_day",:description => hol.description || "Some cool description here...", :start => "#{hol.h_date.iso8601}", :end => "#{hol.h_date.iso8601}"}
		end
		 events
	else
	  params[:for_year]=Time.now.strftime("%Y") unless params[:for_year]
		events = Event.where("YEAR(from_date)=?",params[:for_year]).order("created_at desc")
	end
    respond_to do |format|
      format.html 
	   format.xml  { render :xml => events }
      format.json { render json: events}
    end
  end

it will return the json data as below

[
	{
	created_at: "2013-10-24T06:32:50Z",
	days: 1,
	from_date: "2013-10-26T00:00:00Z",
	id: 6,
	event_type_id: 3,
	reason: "Event",
	to_date: "2013-10-26T00:00:00Z",
	updated_at: "2013-10-24T06:32:50Z",
	user_id: 11
	},
   {
	created_at: "2013-10-24T06:32:14Z",
	days: 1.5,
	from_date: "2013-10-28T00:00:00Z",
	id: 5,
	event_type_id: 13,
	reason: "new Event",
	to_date: "2013-10-29T00:00:00Z",
	updated_at: "2013-10-24T06:32:14Z",
	user_id: 9
	},
	{
	created_at: "2013-10-24T06:30:31Z",
	days: 0.5,
	from_date: "2013-10-25T00:00:00Z",
	id: 4,
	event_type_id: 13,
	reason: "personal work",
	to_date: "2013-10-25T00:00:00Z",
	updated_at: "2013-10-24T06:30:31Z",
	user_id: 8
	}
]

Change the “eventAfterRender” method in jquery

$(document).ready(function() {
		var date = new Date();
		var d = date.getDate();
		var m = date.getMonth();
		var y = date.getFullYear();

		$('#calendar').fullCalendar({ 
		        height: 350,
		        color: '#ff0000',
				textColor: '#ffffff',
				backgroundColor: 'red',
				firstDay: 1,
		        theme: true,
			header: {
				left: 'prev,next today',
				center: 'title',
				right: 'month,agendaWeek,agendaDay'
			},
			disableDragging: true,
			editable: true,
			eventSources: [{
			url: '/yourdata',					
			color: '#ff0000',
			textColor: '#ffffff',
			backgroundColor: '#ccc',
			border:'1px solid #7BD148',
			ignoreTimezone: false
		   }],
        eventRender: function(event, element, date ) {
            element.attr('title', event.tip); // for tooltip
        },
        eventAfterRender: function(event, element, view) {
		       if (event.half == "1") {
		        // half a day
		        var elementWidth = parseInt(90 * event.day_count);

		        // set width of element
		        jQuery(element).css('width', elementWidth + "px");
		       }
		        if (event.className == "holi_day") {
                $(element).find(".fc-event-title").css({"color": "#0000dd", "font-weight": "bold"  });
               }
        }
	  });
	});

Now the event calendar show the holidy, halfday and fullday as below

event calendar

Advertisements

Implementation of Shorten URL using Bitly in Rails 3.x

URL shortening is a technique on the World Wide Web in which a Uniform Resource Locator (URL) may be made substantially shorter in length and still direct to the required page.

This is achieved by using an HTTP Redirect on a domain name that is short, which links to the web page that has a long URL. This is especially convenient for messaging technologies such as Twitter and Identical which severely limit the number of characters that may be used in a message.

Many web developers pass descriptive attributes in the URL to represent data hierarchies, command structures, transaction paths or session information. This can result in URLs that are hundreds of characters long and that contain complex character patterns. Such URLs are difficult to memorize and manually reproduce. As a result, long URLs must be copied-and-pasted for reliability. Thus, short URLs may be more convenient for websites.

Step#1

First create an account at bit.ly  “https://bitly.com/a/sign_up?rd=/”
Get your API key by thefollowing URL

“http://bit.ly/account/your_api_key/”

Step#2

In rails 3.x, write the following gems in your gemfile

 gem ‘bitly’

Run “bundle install”

Step#3

Add the following code in your controller

require ‘bitly’

Step#4

Bitly recently released their version 3 API. From this 0.5.0 release, the gem will continue to work the same but also provide a V3 module, using the version 3 API. The standard module will become deprecated, as Bitly do not plan to keep the version 2 API around forever.

To move to using the version 3 API, call in you top of the controller:

Bitly.use_api_version_3

Step#5

To shorten a URL

bitly = Bitly.new(‘your-bitly-user-id’,’your-bitly-api-key’)

page_url = bitly.shorten(‘your-url’)

shorten_url = page_url.shorten

It will generate the bitly URL like “http://bit.ly/7BWXcQ

Validate RSS or ATOM feeds using FeedValidator in Rails

FeedValidator is an interface to the W3C Feed Validation online service based on its SOAP 1.2 support. It helps to find errors in RSS or ATOM feeds. In Rails app this can be done installing the gem.

Step#1

You can install FeedValidator as a gem by writing in gem file:

gem  ‘feedvalidator’

Run   bundle install  to install the gem

Step#2

Include the require ‘feed_validator’ into your controller

Step#3

Create a migration file and edit the file to add the following fields.

class CreateFeeds < ActiveRecord::Migration
   def self.up
     create_table :feeds do |t|
       t.string :title
       t.timestamps
     end
  end

  def self.down
    drop_table :feeds
  end
end

Step#4

Validate your feed URL in your controller

 def create
    valid = false
    site_url = params[:feed][:title].sub(/(\/)+$/,'')
      begin
        v = W3C::FeedValidator.new
        if v.validate_url(site_url) && v.valid?
          valid = true
          @feed = Feed.new(:title => site_url,
          @feed.save
        end
      rescue
        # Do nothing
      end
    redirect_to request.referrer
  end

Active Record Callbacks in Rails

Callbacks are a great technique for achieving simplicity and flexibility. Callbacks provide a means of hooking into an ActiveRecord object’s life-cycle. A hook is a technique that lets you trap some Ruby event with ActiveRecord, such as object creation. Callbacks are hooks that allow you to trigger logic before or after an alteration of the object state. Callback functions minimizing the length of codes in controllers.

Implementing Callbacks

There are four types of callbacks accepted by the callback macros:

  • Method references (symbol)
  • Callback objects
  • Inline methods (using a proc)
  • Inline eval methods (using a string) – deprecated.

Method references and callback objects are the recommended approaches, inline methods using a proc are sometimes appropriate (such as for creating mix-ins) and inline eval methods are deprecated.
Method Reference

The method reference callbacks work by specifying a protected or private method available in the object, like this:

class Post < ActiveRecord::Base
before_save :process_content

private
def process_content
self.content.strip!
end
end

Callback Objects

The callback objects have methods named after the callback, called with the record as the only parameter such as:

class BankAccount < ActiveRecord::Base
before_save EncryptionWrapper.new(“credit_card_number”)

after_initialize EncryptionWrapper.new(“credit_card_number”)
end

class EncryptionWrapper
def initialize(attribute)
@attribute = attribute
end

def before_save(record)
record.credit_card_number = encrypt(record.credit_card_number)
end

private
def encrypt(value)
# Secrecy is committed
end

end

So you specify the object you want messaged on a given callback. When that callback is triggered the object has a method by the name of the callback messaged.

Proc

Example of using a Proc for a callback:

class Person
before_save Proc.new { |model| model.do_something }
end

Callback Reference

Here are the list of some callback functions

  • before_save

This method is called before an ActiveRecord object is saved.

  • after_save

Once the active record object saved some method will be fired in that scenario we have to use the after_save callback.

  • before_create

Called before creating a new object of the model

  • after_create

Called after creating new object and just before saving the records

  • before_update
  • after_update
  • before_validation
  • after_validation
  • before_validation_on_create
  • after_validation_on_create
  • before_validation_on_update
  • after_validation_on_update
  • before_destroy
  • after_destroy

Grab RSS feeds content from blog site using jquery

Sometime we need our blog website content as a widget in website. Its a quite easy process using zRSS Feeds reader

Download the latest version of zRSS feed here

Include the jQuery and zRSSFeed libraries in your page

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js&#8221; type=”text/javascript”></script>
<script src=”jquery.zrssfeed.min.js” type=”text/javascript”></script>

Add a DIV tag where you want to display the feed as widget and give it an ID

<div id=”my_blog_content”></div>

Now add the script to call the zRSSFeed plugin with the RSS URL and any options. Our example gets 10 feeds from the Reuters site.

<script type=”text/javascript”>
$(document).ready(function () {
$(‘#my_blog_content’).rssfeed(‘http://feeds.reuters.com/reuters/businessNews&#8217;, {
limit: 10
});
});
</script>

By default it returns all data with non css format . Override the css to file in your website like

<stylesheet>

#my_blog_content .rssHeader{
display:none;
}
#my_blog_content .rssBody ul{
margin:0px;
padding:0px;
}
#my_blog_content .rssBody ul li{
list-style:none;
}
#my_blog_content .rssBody ul li div{
font-size:9px;
fint-weight:bold;
}
#my_blog_content .rssBody ul li h4{
margin-bottom:3px;
}
#my_blog_content .rssBody ul li a{
color:#fff;
}
#my_blog_content .rssBody ul li a:hover{
color:#fff;
text-decoration:underline;
}
</stylesheet>

 

Complete example

In veiw file

 

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml&#8221; xml:lang=”en” lang=”en”>
<head>

<meta http-equiv=”content-type” content=”text/html; charset=utf-8″ />
<meta http-equiv=”content-language” content=”en” />

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js&#8221; type=”text/javascript”></script>
<script src=”jquery.zrssfeed.min.js” type=”text/javascript”></script>

<title>Grab posts from Blog</title>

<script type=”text/javascript”>
$(document).ready(function () {
$(‘#my_blog_content’).rssfeed(‘http://feeds.reuters.com/reuters/oddlyEnoughNews&#8217;);
});
</script>
<stylesheet>
#my_blog_content .rssHeader{
display:none;
}
#my_blog_content .rssBody ul{
margin:0px;
padding:0px;
}
#my_blog_content .rssBody ul li{
list-style:none;
}
#my_blog_content .rssBody ul li div{
font-size:9px;
fint-weight:bold;
}
#my_blog_content .rssBody ul li h4{
margin-bottom:3px;
}
#my_blog_content .rssBody ul li a{
color:#fff;
}
#my_blog_content .rssBody ul li a:hover{
color:#fff;
text-decoration:underline;
}
</stylesheet>
</head>
<body>
<h4>Data</h4>
<div id=”my_blog_content”></div>
</body>
</html>

Working with submenu in RefineryCMS

Working with menu and sub-menu is quite easy in refineryCMS but I just cramped while displaying the submenus. Below are the code snippets i found to solve this issue

Call the partial file in your header

=render(:partial => “/refinery/menu”, :locals => { :dom_id => ‘menu’, :css => ‘menu’})

Write the following in your partial menu file

<%
# Collect the root items.
# ::Refinery::Menu is smart enough to remember all of the items in the original collection.
if (roots = local_assigns[:roots] || (collection ||= refinery_menu_pages).roots).present?
dom_id ||= ‘menu’
css = [(css || ‘menu clearfix’)].flatten.join(‘ ‘)
hide_children = Refinery::Core.menu_hide_children if hide_children.nil?
-%>
<ul>
<%= render :partial => ‘/refinery/menu_branch’, :collection => roots,
:locals => {
:hide_children => hide_children,
:sibling_count => (roots.length – 1),
:menu_levels => local_assigns[:menu_levels],
:apply_css => true #if you don’t care about class=’first’ class=’last’ or class=’selected’ set apply_css to false for speed.
} -%>
</ul>
<% end -%>

Write the following in your partial menu_branch file

<%
# Collect the root items.
# ::Refinery::Menu is smart enough to remember all of the items in the original collection.
if (roots = local_assigns[:roots] || (collection ||= refinery_menu_pages).roots).present?
dom_id ||= ‘menu’
css = [(css || ‘menu clearfix’)].flatten.join(‘ ‘)
hide_children = Refinery::Core.menu_hide_children if hide_children.nil?
is_selected_branch = ( selected_page_or_descendant_page_selected?(local_assigns[:menu_branch]) ? true : false)
-%>

<%roots.each_with_index do |page, index| %>
<% if page.children.present? && (children = page.children unless hide_children).present? && is_selected_branch && (!local_assigns[:menu_levels] || page.ancestors.length < local_assigns[:menu_levels])%>
<% page.children.each do |child| %>
<ul class=”firstLevelMenu”>
<li>
<%= link_to child.title, refinery.url_for(child.url)%>
</li>
</ul>
<%end%>
<% page.children.each do |child| %>
<%if child.children.present? %>
<ul class=”secondLevelMenu” style=”display: block”>
<% child.children.each_with_index do |grandchild,i|%>
<li>
<%= link_to grandchild.title, refinery.url_for(grandchild.url)%>
</li>
<%end%>
</ul>
<%end%>
<%end%>
<%end%>
<%end%>

<%end%>

Import data from excel to mysql in rails3 using roo gem

Roo gem allows us to access the contents of

  • Open-office spreadsheets (.ods)
  • Excel spreadsheets (.xls)
  • Google (online) spreadsheets
  • Excel’s new file format .xlsx

Following is a basic example to demonstrate how to get the datas from an excel sheet and save to your database. Suppose you have an excel sheet named student_details.xls which contain the student details such as “Name”,”Phone”,”Address”.We have to save them in our database but it will take a huge time if we insert them manually.Here we can user “roo” gem to fetch the datas from excel sheet and save to database in a fly.

Step#1

Add the gem in your gem file

gem ‘roo’

Then run the bundle

bundle install

Step#2

Place your excel sheet in the rails application such as in public folder.

Step#3

Now its time to change your controller like below.

Add the following line in your controller

require ‘roo’

Create a new method where you will fetch the data from excel sheet and save it in your database.

def  fetch_excel_data

ex = Excel.new(“#{Rails.root}/public/student_details.xls”)
ex.default_sheet = ex.sheets[1] #Mention the sheet number
3.upto(1000) do |line| #start and end of row
name = ex.cell(line,’A’)
phone = ex.cell(line,’B’)
adr = ex.cell(line,’C’)

@student = Student.create(:name => name,:phone => phone,:address => adr)

end
end

when you call this method the roo gem will fetch the datas accordingly and save to your database.