Thursday, 30 August 2012

simplest way to comment in rhtml


The simplest way to do this is to define an a comment method in the application_helper.rb:

def comment(&block)
 #block the content
end

And use it in rhtml templates
<% comment do %>
  .. Some HTML
  .. Some ruby scriptlets
<% end %>


How this works:


def x(&block) # x is a 0 param function                                                                
    y(block) # y is a 1 param function (taking one "Proc")                                    
    z(&block) # z is a 0 param function (like x) with the block x received              
end                                                                                                                         



So, if you call z(&block) it's (nearly!!) the same as calling z { yield }: You just pass the block to the next function.

know the controller and action in view



Just write the below code in your  to know current controller name in a view the right path is

<%= controller.controller_name %>
<%= controller.action_name %>

Wednesday, 29 August 2012

Create a New app Using Mongo db



create new repository using this command:

$ rails new <app_name> -T -O

Use the -T -O flags to skip Test::Unit files and Active Record files.

Ex: $ rails new example_mongo -T -O

include this gems in your gem file:


gem "mongoid", "~> 2.2"    
gem "mongo", "~> 1.5.0.rc0"
gem "bson", "~> 1.5.0.rc0"
gem "bson_ext", "~> 1.5.0.rc0"

go to the repository and run $ bundle update command.

then run $ rails g mongoid:config to generate your configuration file.

try to create a table using scaffold

exp: $ rails g scaffold user name:string email:string

Every thing should go fine... That's it..
:)




Mongoid::Paperclip


Mongoid::Paperclip - Making Paperclip play nice with Mongoid 

1st Install Image Magick using

$ sudo apt-get install imagemagick

As the title suggests: Mongoid::Paperclip makes it easy to hook up Paperclip with Mongoid.
This is actually easier and faster to set up than when using Paperclip and the ActiveRecord ORM. This example assumes you are using Ruby on Rails 3 and Bundler. However it doesn't require either.

Setting it up

Simply define the mongoid-paperclip gem inside your Gemfile. Additionally, you can define the aws-s3 gem if you want to upload your files to Amazon S3. You do not need to explicitly define the paperclip gem itself, since this is handled bymongoid-paperclip.
Rails.root/Gemfile - Just define the following:
gem "mongoid-paperclip", :require => "mongoid_paperclip"
gem "aws-s3",            :require => "aws/s3"
Next let's assume we have a User model and we want to allow our users to upload an avatar.
Rails.root/app/models/user.rb - include the Mongoid::Paperclip module and invoke the provided class method
class User
  include Mongoid::Document
  include Mongoid::Paperclip

  has_mongoid_attached_file :avatar
end

That's it

That's all you have to do. Users can now upload avatars. Unlike ActiveRecord, Mongoid doesn't use migrations, so we don't need to define the Paperclip columns in a separate file. Invoking the has_mongoid_attached_file method will automatically define the necessary :avatar fields for you in the background.

include  :html => { :multipart => true } for form.

Friday, 24 August 2012

Mongo Restart/connection failure ?






Connection failed during mongo start:


Follow this steps:
  • $   sudo rm /var/lib/mongodb/mongod.lock
  • $   mongod --repair
  • $   sudo start mongodb
  • $   sudo status mongodb
  • $   mongo
                      connection established message will be displayed.  :)

Gem File and Gem Lock file



The Gemfile is where you specify which gems you want to use, and lets you specify which versions.

The Gemfile.lock file is where Bundler records the exact versions that were installed. This way, when the same library/project is loaded on another machine, running bundle install will look at theGemfile.lock and install the exact same versions, rather than just using the Gemfile and installing the most recent versions. (Running different versions on different machines could lead to broken tests, etc.) You shouldn't ever have to directly edit the lock file.

Thursday, 23 August 2012

is ajax request (rails)?

if request.xhr?
  # respond to Ajax request
else
  # respond to normal request
end

ajax->success(), complete() methods difference



             All of jQuery's ajax methods return a jqXHR object that provides .error(),.success(), and .complete() methods. So, the difference between.success() and .complete() is .success() only gets called if your web server responds with a 200 OK HTTP header - basically when everything is fine.

                   However, .complete() will always get called no matter if the ajax call was successful or not - maybe it outputted errors and returned an error - .complete() will still get called.


Tuesday, 21 August 2012

Difference between Rails 2.3 and 3


(1) Introduction of bundler (New way to manage your gem dependencies) 
(2) Gemfile and Gemfile.lock (Where all your gem dependencies lies, instead of environment.rb) 
(3) A new .rb file in config/ folder, named as application.rb
 (Which has everything that previously environment.rb had) 
(4) Change in SQL Structure: Model.where(:activated => true) 
(5) All the mailer script will now be in app/mailers folder, 
earlier we kept inside app/models. 
(6) Rails3-UJS support. for links and forms to work as AJAX, 
instead of writing complex lines of code, we write :remote => true 
(7) HTML 5 support. 
(8) Changes in the model based validation syntax: validates :name, :presence => true 
(9) Ability to install windows/ruby/jruby/development/production specific gems to Gemfile. 
group :production do 
 gem 'will_paginate' 
end

JSON



JSON: JavaScript Object Notation.

It is syntax for storing and exchanging text information. Much like XML and is smaller than XML, and faster and easier to parse.

JSON syntax is a subset of the JavaScript object notation syntax.
  1. Data is in name/value pairs
  2. Data is separated by comma
  3. Curly brackets holds objects
  4. Square brackets holds arrays

To validate JSON-

http://json.bloople.net/ with clear pictorial representation

http://jsonlint.com/

Wednesday, 8 August 2012

Polymorphic Associations


polymorphic associations:

                      With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here’s how this could be declared

class Picture < ActiveRecord::Base
  belongs_to :imageable, :polymorphic => true
end

class Employee < ActiveRecord::Base
  has_many :pictures, :as => :imageable
end

class Product < ActiveRecord::Base
  has_many :pictures, :as => :imageable
end




Tuesday, 7 August 2012

What and Why Mongo DB?


                     We built MongoDB from our own experiences building large scale, high availability, robust systems. We didn’t start from scratch, we really tried to figure out what was broken, and tackle that. MongoDB is that if you take MySql, and change the data model from relational to document based, you get a lot of great features: embedded docs for speed, manageability, agile development with schema-less databases, easier horizontal scalability because joins aren't as important. There are lots of things that work great in relational databases: indexes, dynamic queries and updates to name a few, and we haven’t changed much there. For example, the way you design your indexes in MongoDB should be exactly the way you do it in MySql or Oracle, you just have the option of indexing an embedded field.

Why MongoDB?

  • Document-oriented

    • Documents (objects) map nicely to programming language data types
    • Embedded documents and arrays reduce need for joins
    • Dynamically-typed (schemaless) for easy schema evolution
    • No joins and no multi-document transactions for high performance and easy scalability
  • High performance

    • No joins and embedding makes reads and writes fast
    • Indexes including indexing of keys from embedded documents and arrays
    • Optional streaming writes (no acknowledgements)
  • High availability

    • Replicated servers with automatic master failover
  • Easy scalability

    • Automatic sharding (auto-partitioning of data across servers)
    • Reads and writes are distributed over shards
    • No joins or multi-document transactions make distributed queries easy and fast
    • Eventually-consistent reads can be distributed over replicated servers
  • Rich query language

Ruby and Rails



Ruby :
                Ruby is a pure object-oriented programming language with a super clean syntax that makes programming elegant and fun. Ruby successfully combines Smalltalk’s conceptual elegance, Python’s ease of use and learning, and Perl’s pragmatism. Ruby originated in Japan in the early 1990s, and has started to become popular worldwide in the past few years as more English language books and documentation have become available.

Rails:
                      Rails is an open source Ruby framework for developing database-backed web applications.
                      What’s special about that? There are dozens of frameworks out there and most of them have been around much longer than Rails. Why should you care about yet another framework? What would you think if I told you that you could develop a web application at least ten times faster with Rails than you could with a typical Java framework? You can–without making any sacrifices in the quality of your application! How is this possible? Part of the answer is in the Ruby programming language. Many things that are very simple to do in Ruby are not even possible in most other languages. Rails takes full advantage of this.
                    The rest of the answer is in two of Rail’s guiding principles: less software and convention over configuration. Less software means you write fewer lines of code to implement your application. Keeping your code small means faster development and fewer bugs, which makes your code easier to understand, maintain, and enhance. Very shortly, you will see how Rails cuts your code burden. Convention over configuration means an end to verbose XML configuration files–there aren't any in Rails! Instead of configuration files, a Rails application uses a few simple programming conventions that allow it to figure out everything through reflection and discovery. Your application code and your running database already contain everything that Rails needs to know!

Difference between collect and collect!




Collect and collect!

here is an exapmle:


1.9.3p194 :001 > a=[1,2,3]

1.9.3p194 :003 > puts a.collect{|x| x * 3 }
3
6
9
 => nil
1.9.3p194 :004 > puts a
1
2
3
 => nil
1.9.3p194 :005 > puts a.collect!{|x| x * 3 }
3
6
9
 => nil
1.9.3p194 :006 > puts a
3
6
9
 => nil

So, when we use "collect" a dummy array is created and that will be changed.. but not the original array 'a' . Where as in collect!.... original array itself get changed.