Rails 4: Changeset

Tags

, , , , ,

Hey Everyone,

I know, I am very late in posting this article, as I didn’t get chance to do much hands-on in Rails 4. But now, that we all are on the same page, let me quickly set the summary here.

Most of us (1) have already started with Rails4, most of them (2) are planning to and most of them (3) are still on Rails 3. So my target audience for this post is #2 and #3. Developers working on Rails4, if they wish to provide any comments/suggestions they are most welcome.

Recently, I got a chance to develop a new application in Rails4. There are many articles available online, which will provide you insight about the changeset in Rails4. But my idea is to give a step by step information, as I continue to work on my existing application. Hence, this post will keep updating at regular intervals.

Folks can take the information from here which is relevant to them.

- If you wish to localize your gems (including Rails4), to your application, you must need to run:

After, rails new {APP_NAME}, then your bundle runs. Once it is finished, run this command:
bundle install --path vendor/gems

This command will create a .bundle folder inside your app. If you open this folder, there is a config file, where path of the gems is defined. You don’t need to define the path again and again. This config file will take care of it.

- If you have a pending migration and you’re trying to browse your application, Rails tells you to do a rake db:migrate before you see you app in action. See attached screenshot for more reference.

Pending Migration Rails4

- Including modules in Rails4: If you wish to include any re-usable module in a common place (say application_controller.rb) from your {Rails.root}/lib folder, then you must need to tell your application to load the path. To do this, type:
config.autoload_paths += %W(#{config.root}/lib)

- Model.find_or_create_by_{COLUMN_NAMES} is deprecated in Rails4. To use it:
Model.where(col_1: SOME_VALUE, col_2: SOME_VALUE).first_or_create

- ActiveRecord::Relation is now changed to #<ActiveRecord::Associations::CollectionProxy []>

- using of conditions while defining associations is no longer supported. Till Rails 3, one can use this syntax:

- Adding Stylesheets: If you’re trying to add any stylesheet into layout, You must need to add it under ‘config/initializers/assets.rb’
Rails4 shows it in a very beautiful way (refer to the attached screenshot)

assets handling in rails4

assets handling in rails4

- ActionMailer: deliver_now & deliver_later: Action Mailer is now integrated with Active Job so that you can send emails outside of the request-response cycle, hence the user doesn’t have to wait for the request to complete.

However, if you wish to send the mail straightaway, use deliver_now.

UserMailer.welcome_mail(@user).deliver_later
UserMailer.welcome_mail(@user).deliver_now

Kick-Off: First Rails 4 Application with HABTM Association

Tags

, , , , ,

Hello Folks,

Its been a long time since I’ve not written a post. Now, I realize that it’s time to share some useful snippet with all of you.

Recently, I got a chance to get my hands cleaned with Rails 4. So much is happening around Rails community and with the rapid development of Rails 4, I was finding it bit difficult to keep my momentum going.

Well, leave all this apart. Now, by putting some extra efforts my system is ready with:

Ruby 2.1 & Rails 4.1

In order to start with my first Rails 4 Application, I took HABTM Association (weird, isn’t it?). It came randomly into my mind. However, I will dig into other associations as well with time, but to start with let’s take HABTM association with example.

I assume most of you are aware what changes Rails 4 has introduced. If you’re new to Rails 4 or would like to re-visit the changes, here’s the most useful link I’ve found. Just take a look.

Once you’re sure about changeset in Rails4, let’s draw an example:

Prerequisites:

  • Ruby 1.9.2+
  • Rails 4.1.0+
  • Traditional Database (MySQL/Postgres)

Key-Entities:

  • Person Model
  • Communtiy Model
  • A Join Table

Defining the Relationships & creating tables:

For rest of the code-flow (controllers, views) you can download the zip of the application from my GitHub page, run it on your local and see Rails4 HABTM in action.

Happy Coding :)

Add duplicate rows in Excel using Ruby

Tags

, , , ,

Happy New Year Folks,

Few days back a friend of mine came to me and said, “I am a RUBY Programmer and I am stuck in a requirement, wherein I have to read an excel-sheet (that contains multiple records and each record can have multiple entries in it.)”

Think of an example like given in the link: timesheet. It says we have 2 columns: EmployeeID and WorkingHours. Each EmployeeID can have multiple working hours.

Now, I would like to write a small Ruby program that iterate over each record in the excel, combine EmployeeID’s that has multiple entries and add working hours.

Let’s code it then!

Requirements:

  • Ruby 1.9.2 or higher
  • Spreadsheet gem: to read Excel
  • Download timesheet excel from the link above

Happy Coding! :)

Installing mysql2 gem with Ruby 2.0

Tags

, , ,

Hi Folks,

In this short tutorial of mine, I am going to write down the steps of how you can install mysql2 gem with Ruby2.0 on Windows machine.

Installing Mysql gem is always a big time pain for most of the developers who are working on Windows machine. But thanks to active folks over the internet for their comments, posts.

Prerequisites:

1. Ruby 2.0.0 pre-installed.
2. DevKit installed
3. gem install rails – command should install all the gems. Return should be success.

Steps to install mysql gem:
1. Go to: http://dev.mysql.com/get/Downloads/Connector-C/mysql-connector-c-noinstall-6.0.2-win32.zip/from/pick, download will start automatically (don’t think at this moment that you’ve a 32 bit or 64 bit operating system.

2. Extract the folder to some place (in my case I am extracting it to C:\mysql-connector-c-noinstall-6.0.2

3. Run this command:

4. Output will return in below manner:

5. If you see this message, create a new Rails4 application, open your Gemfile and use:
gem 'mysql2', '0.3.13'

and run bundle install. Once bundle install runs successfully. You should try:
rake db:create and
rake db:migrate

to ensure that gem is installed correctly.

Hope this will help someone!

Happy Coding!! :-)

Ruby Cheat-Sheet

Tags

, , , ,

Hi Folks,

In this new tutorial, I am going to show you what most of developers/programmers already know, but not able to keep track of such things. I call it as ‘Ruby cheat-sheet‘, you can call it by the name you like.

This will also help those people who have just started learning ‘Ruby’.

IMPORTANT NOTE:

  • I will keep on updating this article frequently.
  • Also need your valuable response, if you feel there is a better/easy concept available.
  • If I am not sure of something or don’t know the concept, I am going to highlight that with ‘Red‘ color. Later, you can put your opinion in the comment section and I will update that with your name.
  1. Symbols (e.b :name, :age etc.) as just a convenient way of referencing a name.
  2. You don’t need to per-declare a symbol.
  3. A ‘Class‘ is a combination of state (for example, the name of the animal) and method that use that state (perhaps the method how animal eats).
  4. The standard ruby constructor is ‘new‘.
  5. Every object in Ruby has a unique ‘Object identifier‘ (called as Object ID).
  6. Class have instance methods. These instance methods have access to the object’s instance variables.
  7. Methods are defined with the keyword ‘def‘ followed by method name.
  8. The most common way to create String objects in Ruby is ‘string literals‘. (E.g. “I am a string”, ‘I am another string’)
  9. The logical difference between ‘Single quotes‘ and “Double quotes” in Ruby is the amount of processing Ruby does. In double quote case, Ruby first looks for substitution and replaces them with some binary value. (E.g. puts “Good Night, \nAuthor”)
  10. Global variables: starts with ($) sign: E.g. $name
  11. Instance variable: starts with (@) sign: E.g. @name
  12. Class variables: starts with (@@) sign: E.g. @@name
  13. Class name, module name and Constants: Starts with the uppercase letter: E.g class MyClass, module Login
  14. Array stores collection of object with a key to access them.
  15. An array can have objects of different types.
  16. Hash contains key, value pair.
  17. Ruby treats ‘nil’ as false in conditions.
  18. A regular expression is a way of specifying a pattern of characters to be matched in a string.
  19. The match operator (=~) can be used to match a regular expression against a string.
  20. Yield (yield) is a Ruby method
  21. In Ruby, nil is also an Object
  22. When you run Ruby programs you can actually pass arguments. This concept is called command-line-arguments. For e.g. ruby my_example.rb firstname lastname city.
  23. The initialize method in Ruby lets us set the state of each object. When we call ClassName.new to create a new object, Ruby allocates some memory to hold an UN-initialized object.
  24. When we pass an object to puts based on the class, it writes the name of the object’s class, followed by a colon and a unique identifier.
  25. Ruby gives flexibility to its programmers. You can over-write the default methods. (E.g. def to_s)
  26. attr_reader is the modified way of accessor methods.
  27. attr_accessor provides you to read and write methods. (E.g. attr_accessor :age)
  28. Virtual attributes**
  29. require‘, ‘require_relative‘ & ‘load
  30. Access Controls – ‘Public‘, ‘Private‘ & Protected
  31. In ‘Ruby’ a variable is not an Object. It is simply reference to an Object.
  32. initialize‘ is a private method in Ruby.
  33. Block, Procs and Lambda are ways of grouping code we want to run. These are examples of closure in Ruby.
  34. Both Proc and Lambda are Proc Objects.
  35. Lambda check the number of arguments and throws argument error, whereas Proc does not.
  36. In “Inheritance“, if class B inherits the property of class A, then all the methods of class A becomes the member of class B.
    • Assuming child = Child.new; then child.superclass => Parent
    • parent.superclass => Object
    • Object.superclass => BasicObject
    • BasicObject.superclass => nil
  37. Modules: is a way of grouping together Methods, Classes and Constants.
    • Provide namespaces and prevent name clashes.
    • Supports the mix-in functionality.
    • A Module is not a class.
    • A Module cannot have instances.
    • We can always include a module in a class definition – After doing that all module instance methods are suddenly becomes available as methods in the class. They get mix-in.
    • mix-in modules don’t use instance variable directly. They use accessors to retrieve data.
  38. self.method_name: Gives you access to the current object.
  39. begin-rescue blockUse for exception handling.

Displaying Something from The Database

Tags

, ,

Guys in this tutorial I will explain you how to fetch values from the database and show those in a Table format.

Here I assumed one thing, that the user is logged in. and that user has the rights to delete a particular record from the table.

NOTE: This tutorial is very old. But will glimpse you how you can format your data in a structured manner.

So are you Guys Ready???? Then Let’s Start……..

Note: This will start the session of that particular user.

What a leader should learn from M.S. Dhoni

Tags

, , , ,

M.S. Dhoni, yes the world knows him! What he has achieved so far in his cricketing career, nobody else does. He is Indian skipper, known as ‘Maahi’, ‘Capatin Cool’ and lots of other names.

Well, after India became T20 champions and then in 2011 became World champions, soon after that I started hating Dhoni. Trust me, but it’s true. Somewhere in my mind, I thought he is arrogant, proudy and a person who doesn’t respect his seniors and don’t give any value to his team. Trust me when I say this, I mean it.

But in June, 24th 2013, I’ve witnessed of another glory/achivement of Indian team and this time Indian team won the ICC champions trophy 2013 cup. And the Man in highlight is again the Indian skipper M.S. Dhoni.

He was given a team of those players who have either debuting their ODI career or played very limited number of ODI’s or have no experience of playing overseas matches. But in the end, everyone contributed and delivered their best. All credit goes to ‘Maahi’.

What he has done? He showed his trust in #IshantSharma and he proved to be the Game changer/Turning point for #TeamIndia.

* What mantra he (Dhoni) is using?
* Any divine power on him?
* Any Totka he do before every match starts?

Well, the answer to each and every question lies in his Captaincy skills. The way he manages his team, the level of trust he has and the decision making power, the ability to motivate team memeber even if he is not performing and the ability to stay calm, makes him what he is now.

In this article, I am going to talk about what we can learn from Dhoni, how we can adapt some extra ordinary skills and improve ourselves.

Personally, I won’t be giving a lecture kind of thing here.. We all want to be leaders and with the examples like this we can be the masters of our era.

Rails 3: Polymorphic Associations in Action

Tags

,

Hi Folks,

In this short article, I would like to brief about “Rails polymorphic associations“. Below are the high-level pointers.

  • What is Polymorphic Association
  • How Rails handles it
  • Example explained
  • Demo

So, Let’s start:

  • What is Polymorphic Association: In OOP, Polymorphic means “of-many“.

There is a well documented and well explained Railscasts for this. Refer to this link for more information: http://railscasts.com/episodes/154-polymorphic-association

  • Example Explained:

Code snippet can be downloaded from Github. The path for the same is: git@github.com:puneetpandey/rails3_singleTableInheritance.git

Once set-up. Type the URL’s below:

  1. http://localhost:3000/events
  2. http://localhost:3000/users

How to submit your iOS application to Apple store

Tags

, ,

Hi Folks,

For all the iOS developers, who are developing an iOS application and now would like to submit their app to Apple store, all you need is to follow the below steps.

The article is updated according to the latest deployment changes introduced by Apple from March 1, 2013 onwards.

Prerequisite

1. Distribution Certificate

2. Provisioning Profile

3. Xcode 4.6.2

4. iOS 6 and above

5. Mac OS 10.8

6. An iPhone or iPad.

NOTE: I can’t cover how will you get the Distribution and Provisioning certificates and profiles, but in short I’ve created my account on developer.apple.com and the client for whom I worked with, has added me and provided me all the required certificates. But, if you would like to create your own, please read out apple documentation.

1 Distribution certificate: log-in to you developer.apple.com account. Go to -> Certificates, Identifier and Profiles under iOS Developer Program.

  • Click on ‘Certificates’ under iOS Apps.
  • Show the full list under ‘Certificates’ and click on ‘Distribution’.
  • You’ll find a Distribution Certificate (as Type). Download it.
  • Double click on it. It will be open in your ‘Key Chain‘ utility under ‘My Certificates‘.

2. Provisioning Profile: Follow step 1 of Distribution certificate.

  • Click on ‘Certificates’ under iOS Apps.
  • Show the full list under ‘Provisioning Profiles’ and click on ‘Distribution’.
  • You’ll find Distribution Provisioning Profile (as Type). Download it.
  • Double click on it. It will be open in your Xcode.

3. Attach your device with you Mac system and make sure it comes under your ‘Xcode Organizer’ menu.

4. Please keep in mind of below pointers:

  • Make sure your build is clean.
  • Make sure you’ve re-run your build once it’s cleaned.
  • Make sure you’ve run your build on the device to ensure everything is working fine. Because failure of just 1 piece of functionality will not allow you to submit your app to Apple store.
  • Make sure you’ve defined all the dependencies of your application (for e.g. Camera, Maps etc.). Because, when apple reviews your application, it checks weather all the dependencies all defined or not!

5. Your application submission depends on the below steps (we will cover each in detail):

  • Select your connected device near the ‘Run’ button.
  • Set the command line build to Distribution from the drop-down menu.
  • Open info.plist and change the bundle identifier to the appropriate one.
  • Make sure all the launch images are configured/defined properly.
  • Ensure to define distribution certificate under ‘Build Settings’ for Distribution entity.

6. Once all the checks are done. Go to ‘Edit Scheme’ -> ‘Archive’ and change the build configuration on the same window to Distribution.

7. Click on ‘Product’ -> ‘Archive’. This will clean, re-build your application. If no errors found, a new window will open (go to step 8). If error occurs (follow step 4 and 5).

8. You’re almost at the end. In the new window, 2 buttons will be there:

  • Validate and
  • Submit
  • Validate checks if all the required dependencies meet + builds your application
  • Submit validates your application. Requires itnues connect credentials.

I’ll add the necessary screenshots very soon.

Let me know if this article is helpful or need any modification.

Puneet Pandey

Rails 3: Single Table Inheritance

Tags

, ,

Hi Folks/Fellow Developers,

As I’ve seen lot many examples, articles over Single Table Inheritance, I decided to write my own. Thanks to the open source contributors. Their Articles/Examples helped me a lot writing this post.

As you might know about single table inheritance, let me quickly set the definition for it. Single-Table-Inheritance (STI) allows you to write/create sub-classes of a specific model. You can use a single table, add specific objects and extend the functionality/behavior of base model.

Current example explained:

My Current example is based on Mobile system. We have a single model called ‘Mobile’ and other models such as ‘Samsung’, ‘Apple’, ‘Nokia’ etc., that inherits the property of Mobile model. (Refer to the image for more help)

Single Table Inheritance

Single Table Inheritance

Development Platform used:

Ruby - 1.9.3
Rails - 3.2.13
Bundler- 1.3.5
DB - MySQL
IDE - Netbeans 6.9.1

The application is currently hosted on GitHub and can be cloned using the below command:
git clone git@github.com:puneetpandey/rails3_singleTableInheritance.git

Let me know your feedback about this application.

Happy Coding!
Puneet

Follow

Get every new post delivered to your Inbox.

Join 199 other followers