Sunday, 8 November 2015

Rails: Grouping the records by group_by method

Many times we come across such situations where we need to group records, like when we want to display grouped messages, email, alerts .etc based on date or time. Here is the simple code which provides a significant use of group_by method.

Controller Part

class MessagesController < ApplicationController
 def index
   @message = Message.all

   #Retrives all messages and divides into two groups todays messages and other messages
   @grouped_messages = @message.group_by{ |t| t.created_at.to_date == DateTime.now.to_date }

   if @grouped_messages[false].present?
     #Create month wise groups of messages      
     @month_wise_sorted_alerts  = @grouped_messages[false].group_by{ |t| t.created_at.month}
   end    
 end
end


@message.group_by{ |t| t.created_at.to_date == DateTime.now.to_date }


The above line return us the messages in Ordered Hash with two keys true and false on which the messages which are of today's date will be values in true key and others will be values in false.


@grouped_messages[false].group_by{ |t| t.created_at.month }


Above line will provide us the monthwise sorting of the messsages. It will create the Ordered Hash with keys as the month numbers and values as the messages according to their month numbers.


View Part


<h1>Messages</h1>

<!-- Todays messages -->

<% if @grouped_messages.present? && @grouped_messages[true].present? %>
 <h3> Today </h3>
 <% @grouped_messages[true].each do |msg| %>
   <%= msg.content %>
   <%= msg.created_at.strftime('%I:%M %p') %>
   <br />
 <% end %>
 <br />
<% end %>


<!-- Month wise sorted messages -->

<% if @month_wise_sorted_alerts.present? %>
 <% @month_wise_sorted_alerts.each do |hash_elements|%>
 <h3> <%= Date::MONTHNAMES[hash_elements.first] %> </h3>
 <% hash_elements.last.each do |msg| %>
   <%= msg.content %>
   <%= msg.created_at.strftime('%b %d') %>
   <br />
 <% end %>
 <br />
 <% end %>
<% end %>


We can use rails helper to get the month name Date::MONTHNAMES[--month_number--] to get the name of the month in the view.



Grouped Messages

You can also use the gem https://github.com/ankane/groupdate to get more functionality.

References:

  • http://apidock.com/rails/Enumerable/group_by

Saturday, 17 October 2015

OOP Polymorphism

Definition: "Poly" stands for "many" and "morph" stands for "forms". Generally, polymorphism means one name different uses. Technically, it means being able to send the same message to different objects and get different result.

Polymorphism through Inheritance
We can achieve polymorphism through inheritance. For example

class GenericParser
 def parse
   raise NotImplementedError, 'You must implement the parse method'
 end
end

class JsonParser < GenericParser
 def parse
   puts 'An instance of the JsonParser class received the parse message'
 end
end

class XmlParser < GenericParser
 def parse
   puts 'An instance of the XmlParser class received the parse message'
 end
end

Here the GenericParser is the base class. Class JsonParser and XmlParser are inherited from the GenericParser.

Now suppose we run the below code.

puts 'Using the XmlParser'
parser = XmlParser.new
parser.parse

puts 'Using the JsonParser'
parser = JsonParser.new
parser.parse

The output of the above code will be as following.

OUTPUT:
Using the XmlParser
An instance of the XmlParser class received the parse message

Using the JsonParser
An instance of the JsonParser class received the parse message

Here we can see that the same parse method behaves differently for other classes based upon it is called form which object.

               
OOP Polymorphism with DuckTyping
In Ruby, traditional methods of polymorphism (seen above and in languages such as Java) are not widely accepted. A concept known as "duck typing" is preferred.

class GenericParser
  def parse(parser)
    parser.parse
  end
end

class XmlParser
  def parse
    puts 'An instance of the XmlParser class received the parse message'
  end
end

class JsonParser
  def parse
    puts 'An instance of the JsonParser class received the parse message'
  end
end

Here we do the same thing now without inheritance. We write the code as below.

parser = GenericParser.new
puts 'Using the XmlParser'
parser.parse(XmlParser.new)

puts 'Using the JsonParser'
parser.parse(JsonParser.new)
The output of the code is as below.

OUTPUT:

Using the XmlParser
An instance of the XmlParser class received the parse message

Using the JsonParser
An instance of the JsonParser class received the parse message

Here we can see that the same method parser.parse behaves differently on the basis of the which of object is passed as a parameter. It calls particular parse method on the basis of which type of object is passed.

Notice that the method behaves differently depending on the object that receives it’s message. This is polymorphism!

References:





Saturday, 3 October 2015

5 Useful Android Apps

There are many apps available for Android but these are some useful apps which I use regularly.

1. Money View: Financial Planning


Description: With the Free Money View app, you get a real-time visibility into your entire Personal Finances. It works by itself without any manual data entry - their daily expense manager app organizes our financial summary by analyzing SMS sent by our bank and billers to our phone. The app auto-tracks your expense, bills and account balances across all our financial accounts to help us stay on top of our money. The app is highly secure as it never reads any sensitive data - no full bank account numbers, no OTP, and no Netbanking login/password.

As it anaylzes the money transactions via the SMS in our phone it is highly useful app for tracking our expenses, so we can know our money is going in which direction so we can control it.





More information: 
https://play.google.com/store/apps/details?id=com.whizdm.moneyview&hl=en

2. Any.do To-do List | Task List


Description: This app is usually task management app with lots of cool features. The main benefit is web, mobile, desktop and tablet support. You can create the notes with reminders which reminds you about every single task. Even when there is a miss call on your phone, it generates a pop up with the choices to call them instantly or remind you after 15 mins, 1 hour or later as per the time that you choose to be reminded. You can simply drag your tasks to do them today,tomorrow or someday as you wish. Every morning at 9:00 AM it reminds your tasks and plan your day.

So it as also a cool task management app to have which can increase your day-to-day productivity.


 


More information: 
https://play.google.com/store/apps/details?id=com.anydo&hl=en

3. Inbox by Gmail


Description: Inbox, built by the Gmail team, keeps things organized and helps you get back to what matters. Get the most important information without even opening the message. Check-in for flights, see shipping information for purchases, and view photos from friends right up front.Similar messages are bundled together so you can deal with them all at once. And get rid of them with one swipe. More than mail, you can add Reminders so your inbox contains all the things you need to get back to. Snooze emails and Reminders to come back when you are ready to deal with them: next week, when you get home, or whenever you choose. 

A really cool app by Google with lots of cools features.


 


More information: 

4. MX player


Description - The best way to enjoy your movies. If you are a movie manic this is a must have app for you. Scrolling on the left and right side on your player increase and decreases the brightness and the volume respectively. MX Player is the first Android video player which supports multi-core decoding. Test result proved that dual-core device’s performance is up to 70% better than single-core devices.Easily zoom in and out by pinching and swiping across the screen. Zoom and Pan is also available by option.Scroll forward/backward to move to next/previous text, Up/down to move text up and down, Zoom in/out to change text size.

One of the best video players out there.






More description: 
https://play.google.com/store/apps/details?id=com.mxtech.videoplayer.ad&hl=en

5. ES File Explorer File Manager


Description: Manage your files just like you do on your desktop or laptop using Multiple Select, Cut/Copy/Paste, Move, Create, Delete, Rename, Search, Share, Send, Hide, Create Shortcut, and Bookmark. All operations can be performed on local files (on your Android device) or even remotely (from your computer over a network). Categorize, uninstall, back up, and create shortcuts to your appsAllows you to compress and decompress ZIP files, unpack RAR files. Including photos, music, and videos; supports third-party applications such as Quick Office for better productivity.

A file manager with a really cool UI design, easy to access and elegant.


 



More description: 


References: