Monday 15 April 2013

Ruby Modules && Mixins

include and extend in ruby

Today I would like to explain differences between include  and extend in Ruby.
Include: Include it is adding methods of a class  to an instance which we created.
Extend: Extend it is for adding class methods itself.

If we go with a simple example we can get a clear picture
module Advertisement
def advertisement
puts ‘upgrade to new rails version’
end
end

class Movie
include Advertisement
end

Movie.new.advertisement # upgrade to new rails version
Movie.advertisement # NoMethodError: undefined method ‘advertisement’ for
Movie:Class


class Game
extend Advertisement
end


Game.advertisement # upgrade to new rails version
Game.new.advertisement # NoMethodError: undefined method ‘advertisement’ for #<Game:0x1e708>


So that from above example we can get a basic idea that “include” makes the advertisement method available to an instance of a class
and where as the extend makes the advertisement method available to the class itself.

Monday 8 April 2013

form_for and form_tag

I would like to explain differences between form_for and form_tag

form_tag and form_for both are used to submit the form and it’s elements. The main difference between these two is the way of managing objects related to that particular model is different.

form_for:

We should use “form_for” tag for a specific model i.e. while crating a new row in database. It performs the “standard http post” which is having fields related to active record (model) objects.

Example for how to use form_for tag:

<% form_for :user, @user, :url => { :action => "update" } do |f| %>

After this, we can use the f as an object to create input filed.

Username: <%= f.text_field :username %>
Email : <%= f.text_field :email %>
Address: <%= f.text_area :address %>

<% end %>

form_tag:

It creates a form as a normal form. form_tag also performs the “standard http post” without any model backed and has normal fields. This is mainly used when specific data need to be submitted via form.


Example:

<% form_tag '/articles' do -%>
<%= text_field_tag "article", "firstname" %>
<% end -%>

It just creates a form tag and it is best used for non-model forms.