Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Todd Sayre http://del.icio.us/sporkyy

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Rails ajax star rater

Here's some Rails code I created to try out the CSS Star Rating Redux from Komodo Media.

I set up my routes.rb to use REST.

   1  map.resources :titles, :member => { :rate => :any }


I use the Ruby Linguistics Framework to make this implementation easier. Install it using RubyGems (sudo gem install linguistics). And then put the following code at the top of your application_helper.rb file.

   1  require 'linguistics'
   2  Linguistics::use(:en)  # extends Array, String, and Numeric


This code goes in the page you want the rater to appear in, in this example, show.html.erb.

   1  <ul class="star-rating" id="<%= dom_id(@title) -%>_rating"><%= render :partial => '/partials/star_rating', :locals => { :record => @title } %></ul>


Create a partial called _star_rating.html.erb in your RAILS_ROOT/views/partials directory.

   1  <li class="current-rating" style="width: <%= number_to_percentage((record.rating.to_f * 25) / (5 * 25) * 100) -%>;">Currently <%= record.rating -%>/5 Stars.</li>
   2  <% (1..5).each do |i| -%>
   3      <li><%= link_to_remote pluralize(i, 'Star'), {
   4          :update => "#{dom_id(record)}_rating",
   5          :url => eval("rate_#{record.class.name.downcase}_url(:rating => #{i})")
   6      }, {
   7          :class => "#{i.en.numwords}-#{i.abs == 1 ? 'star' : 'stars'}",
   8          :title => "#{pluralize(i, 'star')} out of 5"
   9      } -%></li>
  10  <% end -%>

FirstLast (real classes for Ajaxability)

I know CSS has the :first-child and :last-child pseudo classes. But :first-child is a part of CSS 2 and has poor browsers support and :last-child is a part of CSS 3 and that's not worth thinking about using yet. The idea is sound though, so I worked up this JavaScript method of getting the same effect.

One advantage of doing this in JavaScript rather than using CSS is that the classes will change if you reorder the child nodes with more JavaScript. In my case I'm using Scriptaculous sortables. Or to be more specific, I'm using a Ruby on Rails helper method to make something sortable through Scriptaculous:
   1  <%= sortable_element 'image-list',
   2      :constraint => false,
   3      :url => { :action => 'sort', :issue_id => params[:issue_id] }
   4  -%>


I've chosen to not make this script run unobtrusively. Most of it can go into a file and be included in the header or added to your own common JavaScript include file. To get it to run on a page you will need to include something like the below in each page.
   1  <script type="text/javascript">
   2  //<![CDATA[
   3      Event.onDOMReady(function(){FirstLast.go("image-list")});
   4      Ajax.Responders.register({
   5          onComplete: function(){FirstLast.go("image-list");}
   6     });
   7  //]]>
   8  </script>

I use the DOMReady extension for Prototype's Event object, but you can use any loader you want. The Ajax.Responders.register part reruns the script after a drag-and-drop operation (or any Ajax operation really).

Download Scriptaculous and Prototype.

   1  var FirstLast = {
   2      go: function(el) {
   3          el = $(el);
   4  
   5          // Whitespace nodes need to be cleaned to get the intended effect
   6          var children = Element.cleanWhitespace(el).childNodes;
   7  
   8          // Return if there are not any children
   9          if (0 == children.length) return
  10          
  11          if (1 == children.length) {
  12              // Cheap shortcut if there is only 1 child node
  13              children[0].addClassName(this._firstChildClassName);
  14              children[0].addClassName(this._lastChildClassName);
  15          } else {
  16              for (var i = 0; i < children.length; i++) {
  17                  switch (i) {
  18                      // First child
  19                      case 0:
  20                          children[i].addClassName(this._firstChildClassName);
  21                          children[i].removeClassName(this._lastChildClassName);
  22                          break;
  23                      // Last child
  24                      case children.length - 1:
  25                          children[i].removeClassName(this._firstChildClassName);
  26                          children[i].addClassName(this._lastChildClassName);
  27                          break;
  28                      // Every child other than the first or last
  29                      default:
  30                          children[i].removeClassName(this._firstChildClassName);
  31                          children[i].removeClassName(this._lastChildClassName);
  32                          break;  // I know it is unnecessary
  33                  }
  34              }
  35          }
  36      },
  37      // Pseudo Private methods and attributes
  38      _firstChildClassName: "first",
  39      _lastChildClassName: "last"
  40  };

PrototypeHelper :with helper

This method is for use in conjuction with the Ruby on Rails Module ActionView::Helpers::PrototypeHelper.

The options hash takes any number of key/value pairs the key becomes the name of the parameter passed in the with value and the value becomes a javascript expression

key — name of the parameter
value — a fragment of javascript that will be the value of the parameter

Example
>> params_for_with(:clean_range => 'clean_range', :raw_range => 'raw_range', :total_count => 'total_count')
=> 'total_count=' + total_count + '&' + 'clean_range=' + clean_range + '&' + 'raw_range=' + raw_range


Don‘t forget you won’t necessarily get the parameters out in the same order you put them in, such is the nature of hashes

   1  
   2  def params_for_with(options = {})
   3      options.collect { |param_name, js_fragment| "'#{param_name}='+#{js_fragment}" }.join("+'&'+")
   4      # or this one
   5      #options.stringify_keys.collect { |param_name, js_fragment| '"' << param_name << '="+' << js_fragment }.join('+"&"+')
   6  end
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS