Home > zooi_gin

zooi_gin

Zooi_gin is a project mainly written in Ruby, based on the MIT license.

Rails jquery data helper

Gin

JS data helper.

Example

A) Basic usage

<% content_for :head do %> <% jquery_ready_tag do |s| %> <% s.element(:body) do |e| %> <% e.data(:page_title, 'My awesome page') %> <% e.data(:posts_path, posts_path) %> <% end %> <% end %> <% end %>

Will render to head:

Data is therefore available to jquery in the usual way:

// set the html of the element with id 'page_title' to 'My awesome page' $('#page_title').html($('body').data('pageTitle'));

// alert the posts path alert($('body').data('postsPath'));

B) Swanky usage:

=# haml

  • content_for :head do
    • jquery_ready_tag do |s|
      • @posts.each do |p|
      • s.element "#post_#{p.id}" do |e|
        • e.data(:id, p.id)
        • e.data(:title, p.title)
        • e.data(:published, p.published)

Will render to head (for a few example post models):

Again, these values are then accessible by jquery in the usual way.

An alternative approach might be to override to_gin in the model:

class Post

...

def to_gin
  { :id => id, :title => title, :published => published }.to_gin
end

end

Then in haml:

  • content_for :head do
    • jquery_ready_tag do |s|
      • @posts.each do |p|
      • s.element "#post_#{p.id}" { |e| e.data('post_data', post) }

Renders:

Then accessed by:

$('#post_1').data('post_data').title

A sensible to_gin override can be generated using the gin_attributes macro:

class Post gin_attributes :id, :title, :published

Through metaprogramming, this effectively the same as above, i.e.:

def to_gin { :id => id, :title => title, :published => published }.to_gin end

C) Locals helper

Assuming @given_name and @surname are 'rod' and 'hull', respectfully:

<%= jquery_locals :first_name => @given_name, :last_name => @surname %>

Will render:

var firstName = 'rod'; var lastName = 'hull';

This could be particularly useful for ajax in js.erb templates.

(todo: change locals so doesn't create global variables!)

Notes:

  • Data keys are converted from snake case to camel case
  • Values are converted to javascript via the to_gin method on the respective object
  • The element 'attr' setter method is included as well as the 'data'. There may be more to follow.
  • The jquery_ready_tag method also accepts the '<<' to append a plain string of js to the script

Copyright (c) 2009 [name of plugin creator], released under the MIT license

Previous:neuralsession