Your SlideShare is downloading. ×
Applied Ruby on Rails and AJAX - Conferences - O'Reilly Media
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Applied Ruby on Rails and AJAX - Conferences - O'Reilly Media

440
views

Published on


0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
440
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
2
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • There are a lot of reasons you would choose ROR.
    First and the most obvious one is that it allows for Rapid Application Development. You can create applications up to 10 times faster than PHP and other languages.
    One of the really impressive characteristics of ROR is the DRY principle which stands for “Do Not Repeat yourself”. This makes for a very disciplined language making web development more Agile than ever before.
    Those of you already experienced with Rails know that Rails is all about normalization. That means you need to have your tables designed in a fully normalized manner which again takes us back to DRY.
    Once you have created an application in Rails, it is really easy to transform your application so it can provide Web Services.
    Last but not least, everything in ROR is an object, like it or not!
    No Kidding!: Everything that can be a variable name is an object.
    Even classes and arrays are objects
    Nil is an object too
    In other programming languages, null refers to “no reference to an object”.
    Won’t get “Null pointer errors” but rather get a NoMethodError
    Not exactly everything is an object, for instance, variable names are an exception and while we are here, blocks are also not objects
    Gems: Easy to add on and extend usability
    Web Services: Easy to make web services
    Making relationships is easy
    Some of you might not agree but one of the best things about ROR is OO
    Simplicity
    More dynamic
    Extend functionality
    Singleton Methods
    Strongly Typed
    More dynamic than Java C++ or PHP
    Extend class functionality at any point for even built in classes
    Singleton methods : methods defined on an object instead of a class. Garfield.sleep where Garfield is a cat
    # class Cat

    # end
    Garfield=Cat.new
    YelloCat = Cat.new
    def Garfield.sleep
    “Sleeping”
    End
    Garfield.sleep would return “sleeping”
    YellowCat.sleep would return “no method error”
    Objects are strongly typed as compared to statically typed
    Ruby is
    Strongly,
    Dynamically,
    Implicitly
    typed.
  • Before I show you the world of ROR we need to take a quick refresher on MVC because it is one of the most important concepts to understand in ROR. Taking a few moments to master this concept will benefit us greatly in the long run. You see, everything in ROR is organized as either a model, a view or a controller.
    End users provide input to controllers which then invoke models and views as needed. If the MVC terminology seems complex you can think of controller as input, model as where the processing is done, and view as the output.
  • Just so I know everyone here is familiar with creating a ROR application, I am gonna go through a very quick crash course in ROR.
    A rails application is created using rails command. Once we execute the command, a shell application is created for us as you can see.
    This creates the bare application. Next you will start your server, [Webrick or Apache etc] and then we are ready to roll on rails
    If you visit your application at this point, you should be greeted with the default welcome message
  • One of the great features of Rails is the power of scaffolding which creates an entire base application complete with CRUD functions from which you can then build upon.
    CRUD functions give you the ability to perform basic functions on a database application such as create, read or retrieve, update or delete.
    But before we can jump into using scaffolding, we need to create a table.
    On the left you are seeing a schema for the table called users. It is important in ROR that your table names be plural, I.e. users instead of user, members instead of member, bookmarks instead of bookmark etc.
    Once we have a table created, we use scaffolding to create our application.
  • This is scaffolding in action. As I said before, all CRUD functions can now be performed without any coding on our part.
    Notice how the applicaiton knows the field names that we created in the users table. Also notice how conveniently the “New user” link is presented.
    Nothing really to explain here. This example show how you create a new user which is then listed on the screen. Next to each record listed, we are presented with the “Show”, “Edit” and “Destroy” links which complete our application.
    Not only was all the CRUD operations enabled for you, all the needed controllers, models and views were also created using which you can then start extending the functionality of your application. In addition, a wealth of functions are also created allowing us to retrieve records from the underlying table. Pretty cool, huh!
  • One of the most useful functions created automatically when we create a model extended from an ActiveRecord model, are the find functions.
    Remember our users table that we created earlier which had 2 fields named email and name. To find records in these tables based on email, name or any other fields, we can call the functions find_by_email or find_by_name and provide as parameters the value of the field to search.
    We can also combine field names and call the function find_by_field_name_and_field_name where different field names can be speficied. Note, that we cannot call find_by_field_name_or_field_name but that may change soon.
    Similarly we have other find functions to use including find_first, find_all_by, find and find_by_sql which are also created for us automatically.
    If we would rather write our queries by hand, and I know many of you do (like me), you can use the find_by_sql function.
    NO other language or framework will do so much for you.
  • Just a quick note to show how URLs in ROR are structured. Understanding the URL structure is key in working with your application.
    The blue part of the URL, in this case posts, tells the application about which controller to invoke. The green part that says reply, informs the application to call the reply action which is a function defined in our posts_controller.rb file.
    The red part is the id, in this case 4 tells our application which record we are operating on. Together the URL tells the application that the user wants to make a reply to a post with the id of 4.
  • Now that we all understand the basics of ROR, lets get down and dirty. Adoppt is a replicatable social networking project where the base application was completed in a record 45 days using Ruby on Rails. The main idea behind adoppt was to let its members create web 2.0 style communities, maintain or syndicate blogs, participate in forum discussions , organize and share favorites and more.
  • This is just a screenshot of the home page of Adoppt which is still currently in Alpha. The diagram on the left gives users an idea of what they can do on Adoppt. On the right hand side we are seeing the top blog post tags that users used to organize their blog entries.
  • Here is a member’s home page who just happens to be my wife. You can see her blogs, access her favorites and see what kind of web sites she likes to bookmark. You can also access all the questions she is asking and hopefully answer some of them.
  • In Adoppt, we wanted to make various forms such as the login form AJAXified so when you click on the login link you will be presented with the login form on the same page.
    On this slide we go from having a regular form to an “AJAXified form” by simply adding a few parameters
    As you can see, we changed the call “link_to” to “link_to_remote”.
    Next, I will show you how the AJAXified form looks.
  • Upon clicking the login link marked with #1 we are presented with the login form without having to leave the page
  • ROR would not be as functional as it is if it wasn’t for the excellent support for creating relationships and performing validations on the forms.
    In this example we see that a community belongs to a member or a system (which is a special kind of member), has many members subscribed to it and many favorites can be posted to it.
    Just below the relationships, are the validations for the Portal model. We are specifying that the portal_name, portal_description and the portal_url all be present when a record is added or edited. We also are making sure that the community/portal URL requested by a member is unique.
  • In the last slide I showed you how a portal has many members through subscriptions.
    Here I will show you how that is carried out.
    Instead of creating a direct HABTM model, we create the missing model named Subscription so our Subscription model can utilize all the benefits of being an ActiveRecord model. The member has many subscriptions, and so does a portal. On the other hand the Subscription belongs to both a member and a portal
  • This is a typical example of a self referential HABTM relationship. The need for this relationship exists in all social networking sites where a member has many friends and each of the friends are also in turn a member. Rails makes it really effortless to create such complicated relations. For instance as you can see on the slide, our Member model has a HABTM relationship with friends. Since a friend is also a member, we must specify the :class_name, which is “Member”.
    The actual relationship between members and their friends will be stored in a table named friends_members which is specified here using the join_table.
    In the friends_members table our foreign key is member_id and our association foreign key is friend_id.
    One important thing to note is the functions specified on after_add and after_remove events which will be called automatically when someone adds or removes a friend.
    This is necessary because if I am your friend, you want to be my friend too or our friendship won’t exist.
    Using the after_add declaration we specify that a function named become_friend_with_friend must be called when a friend is added by a member. Similarly if either of the friend terminates the friendship, the function end_friendship will be called.
  • So far we have been creating various kinds of relationships. Here are some examples of how these relationships are being used.
    For instance, the first example shows which favorites were bookmarked to a portal. We simply create a new portal object and then call the favorites function for that object.
    Next is an example of which members are subscribed to a community. Again after creating a new portal object we simply call the subscriptions function.
    At some point we will want to know which portals a member is subscribed to. In that case we create a new instance of Member model and call the portals function for it.
    Similarly we will want to know which members are friends of another member. So we once again create a new instance of the member model and call the friends function to obtain this information.
    The functions that are used here such as favorites, subscriptions, portals or the friends do not need to be created by you because Rails creates them for you when you create a relationship.
  • On this slide we have an example of a transaction. If using MySQL we need to set our table type to InnoDB to use transactions. What you see in this example is that we create a transaction for our Member class which takes a member and a friend object as parameters.
    The friend will only be added to a member’s friends if he wasn’t already a friend.
    Once the friend is added to a member’s friends we reverse the action and add the member to a friend’s friends.
    The benefit of using transactions is that if either of the specified requests fail, both actions will be rolled back. In other words all or none of the actions specified will be carried out ensuring data integrity.
  • In Adoppt, we wanted a member to be able to claim their blog so it can show up in their profile. But how do we go about ensuring that a blog belongs to a member who is claiming it?
    The best way for a member to prove that a blog belongs to them is to have them place a special encoded key on their blog and then telling us to check for the key.
    Once a member is ready for verification we call the claim_verify function that is shown here. Before we can check for the key on the member’s blog we need to retrieve the encoded key from the database. The claim_verify function retrieves that key by calling the function find_by_url and supplying it the member’s blog url as a parameter.
    The next step is to actually fetch and read the contents of the member’s blog URL and then check for the key. While in other programming languages this can take up several lines of code, in ROR we can perform this task in just one line. The result of whether the key was found is stored in the @found variable. Depending on the value of this variable, we can then update our databases and complete the claim process.
  • Web 2.0 applications just aren’t complete without the support for tagging. Ruby on Rails provides you with at least two ways of implementing tagging in your application. You can either use the acts_as_taggable gem which we used at Adoppt or you can use the acts_as_taggable plugin by David, the creator of Rails.
    Generally when we implement tagging, we can either ask the members to tag a record when they are adding it or have them tag a record after they have added the record. On Adoppt we utilize both methods of asking a user to tag a record.
    On this slide you are seeing a user adding tags to define their blogs after they have claimed it.
    Using AJAX, we tell the user about the number of tags they have left. The tags list is also dynamically updated as the user adds tags.
  • Assuming you are using the acts_as_taggable gem, adding the tagging support to your model is easy as long as you have fully normalized tables. On this slide you are seeing how you would make the Article model taggable using the TagArticle class. In the Article model, we specify the join_class_name to be ‘TagArticle’ and then in the TagArticle model we create the belongs_to relationship and specify the class_name to be Article and the foreign key to be article_id.
    You can also see how we would go about tagging an article and then retrieve the tags assigned to an article object by simply creating a new instance of Article model and then calling the tag function for it..
    Another prominent feature of Web 2.0 and tagging is the tag cloud that you see everywhere online these days. Fortunately, with Rails and the function provided by Tom Fakes, creating the tag cloud is a oneliner. Once the tag cloud has been retrieved, it can be formatted to fit the application’s needs.
    # Tag cloud (Tom Fakes)
  • Ever since the web started, people and professionals alike have complained about the absence of in place editing which simply means that a user should be able to edit a value without having to load a new page.
    With Web 2.0, AJAX and ROR in-place editing is a breeze, easier than ever before.
    On this slide you are seeing all the code required to implement in-place editing. You would need to embed prototype and script.aculp.us javascript libraries to enable this functionality.
    First, we modify our views file and place the call for in_place_editor_field specifying the model, the field and the default value for the in place field editor.
    Next, we modify our model to tell it about the in_place edit field by specifying in_place_edit_for declaration.
    You can also see the end result. By clicking the highlighted text numbered one on the slide, an editing box appears with which you can modify the text and choose either the OK or cancel button when done editing.
  • We have discussed quite a few things in this presentation from creating a barebone application to more complex relations and examples using ROR and AJAX.
    As I said earlier, after gaining significant experience in PHP and other langugages I migrated to ROR and haven’t looked back since. To me ROR isn’t just about a framework, it makes me look at the world of programming in a totally fresh way.
  • There are ton of books and websites offering help on ROR but here are a few of my favorites.
  • Thank you for attending this session,. I hope you have a better understanding of how ROR can be applied in complex web applications. Now is the time when you hammer me with questions. So please go ahead and ask your questions.
  • Transcript

    • 1. Applied Ruby on Rails & AJAX An insight into the technology and principles behind a social networking community
    • 2. Who am I? • Farhan Mashraqi (Frank Mash) • Developer for 7+ years • MySQL DBA • Community Member • A Recovering PHP Developer Contact Information: • Business E-mail: frank@designerzllc.com • Personal E-mail: softwareengineer99@yahoo.com • Personal Blog http://mashraqi.com
    • 3. What we’ll cover (aka the essentials) • Why ROR? • MVC • Crash Course (Scaffolding etc) • URLs in ROR • Adoppt • AJAXifying Forms • Relationships / Validations
    • 4. The essentials continued • Transactions • Blog Claims • Tagging • In place editing • Learn more • Q&A
    • 5. Why would I use Ruby On Rails? • RAD • DRY: “Do not Repeat Yourself” • Disciplined • Normalization • Relationships • Web Services • Everything is an Object
    • 6. MVC
    • 7. Crash Course [root@srv31 docs]# rails ror create create app/controllers create app/helpers create app/models create app/views/layouts create config/environments create components create db create doc create lib create lib/tasks create log create public/images ... Creating a bare application on Rails [root@srv31 docs]# rails ror
    • 8. Do it with Scaffolding [root@srv31 ror]# ruby script/generate scaffold user exists app/controllers/ exists app/helpers/ create app/views/users exists test/functional/ dependency model exists app/models/ exists test/unit/ exists test/fixtures/ create app/models/user.rb ruby script/generate scaffold user CRUD = ‘C’reate, ‘R’ead, ‘U’pdate, ‘D’elete
    • 9. Experience the magic http://localhost:3000/users http://localhost:3000/users/new
    • 10. Find functions • find_by_[field_name] (field_value) • find_by_[field_name]_and_[field_name] • find_first • find_all_by • find() • find_by_sql(‘SELECT ….’)
    • 11. URLs in ROR <%= link_to “Reply”, :controller=>”posts”, :action=>“reply”, :id=>4 %>
    • 12. What is Adoppt • A replicatable social networking platform • Create and participate in communities • Blogs, Forums, Favorites and more
    • 13. Ajaxifying the login form Ajaxified version <%= link_to “Login”, :controller=>”member”, :action=>”login” %> Typical form in ROR <%= link_to_remote “Login”, :url=>{ :controller=>”member”, :action=>”login” }, :update => “loginform”, :loading => “Element.toggle($(‘loading’))”, :complete => “Element.toggle($(‘loading’))” %> Same form ‘AJAXified’
    • 14. Relationships / Validations • A community – Has many members subscribed – Members can post favorite web sites – Belongs to a member or system class Portal < ActiveRecord::Base has_many :subscriptions has_many :favorites belongs_to :member validates_presence_of :portal_name validates_presence_of :portal_description validates_presence_of :portal_url validates_uniqueness_of :portal_url … end
    • 15. HABTM using Subscriptions class Member has_many :subscriptions end class Portal has_many :subscriptions end class Subscription belongs_to :member belongs_to :portal end
    • 16. Self referential relationships • A member has many friends (member) • Self referential HABTM relationship class Member < ActiveRecord::Base has_and_belongs_to_many :friends, :class_name => "Member", :join_table => "friends_members", :association_foreign_key => "friend_id", :foreign_key => "member_id", :after_add => :become_friend_with_friend, :after_remove => :end_friendship end
    • 17. Using relationships @portal = Portal.new @favorites = @portal.favorites 1. Which favorites were posted to a portal 2. Which members are subscribed? @portal = Portal.new @members = @portal.subscriptions @member = Member.new @member_portals = @member.portals 3. Which portals a member is subscribed to? 4. Which members are friends of a member? @member = Member.new @friends = @member.friends
    • 18. Transactions (InnoDB) Member.transaction(@member, @friend) do @member.friends << @friend unless @member.friends.include?(@friend) @friend.friends << @member unless @friend.friends.include?(@member) end
    • 19. Blog Claims def claim_verify @wb= Weblog.find_by_url(@params[:url]) require 'open-uri‘ @found = open(@wb.url).read.include?(@wb.v_key) end
    • 20. Tagging • acts_as_taggable gem (http://taggable.rubyforge.org/)
    • 21. Tagging class Article < ActiveRecord::Base acts_as_taggable :join_class_name => 'TagArticle‘ class TagArticle belongs_to :article, :class_name => 'Article', :foreign_key => 'article_id‘ @tagged = Article.tags_count(:limit => 10) Tagging an article @article = Article.new @article.tag “mysql conference ror” Tags for an article @tags = @article.tags() Tag Cloud (Tom Fakes)
    • 22. In place editing class BlogsController < ApplicationController in_place_edit_for :weblog, :description <%= in_place_editor_field :weblog, :description, :value=>'' %> In your views file In your model
    • 23. Recap • ROR: Valuable to You
    • 24. Where to learn more • Books – Agile Web Development with Rails by Dave Thomas and David Heinemeier Hansson – Pro Rails by me – ROR Recipes by Chad Fowler • Websites – http://www.ruby-doc.org/ – http://www.rubygarden.org/ruby/ – http://www.ruby-lang.org/ – http://www.ruby- doc.org/stdlib/libdoc/rdoc/rdoc/index.html – http://script.aculo.us – http://rubyonrails.adoppt.com/blog/frank
    • 25. Q&A

    ×