Screencast: DataTables

DataTables erleichtert die Erstellung von Tabellen in HTML und unterstützt dabei seitenweise Navigation, Sortierung und Suchen. Ryan zeigt in diesem Screencast wie es in Rails eingesetzt werden kann.

 

Downloads in verschiedenen Formaten:

mp4
m4v
webm
ogg

 

Resourcen:

Gemfile

[ruby]
group :assets do
gem ‚jquery-datatables-rails‘, github: ‚rweng/jquery-datatables-rails‘
gem ‚jquery-ui-rails‘
end

gem ‚will_paginate‘
[/ruby]

app/assets/javascripts/application.js

[javascript]
//= require dataTables/jquery.dataTables
[/javascript]

app/assets/stylesheets/application.css

[css]
/*
*= require jquery.ui.core
*= require jquery.ui.theme
*= require dataTables/src/demo_table_jui
*/
[/css]

app/assets/javascripts/products.js.coffee

[javascript]
jQuery ->
$(‚#products‘).dataTable
sPaginationType: "full_numbers"
bJQueryUI: true
bProcessing: true
bServerSide: true
sAjaxSource: $(‚#products‘).data(’source‘)
[/javascript]

views/products/index.html.erb

[html]
<table id="products" class="display" data-source="<%= products_url(format: "json") %>">
<thead>
<tr>
<th>Product Name</th>
<th>Category</th>
<th>Release Date</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
[/html]

products_controller.rb

[ruby]
def index
respond_to do |format|
format.html
format.json { render json: ProductsDatatable.new(view_context) }
end
end
[/ruby]

app/datatables/products_datatable.rb

[ruby]
class ProductsDatatable
delegate :params, :h, :link_to, :number_to_currency, to: :@view

def initialize(view)
@view = view
end

def as_json(options = {})
{
sEcho: params[:sEcho].to_i,
iTotalRecords: Product.count,
iTotalDisplayRecords: products.total_entries,
aaData: data
}
end

private

def data
products.map do |product|
[
link_to(product.name, product),
h(product.category),
h(product.released_on.strftime("%B %e, %Y")),
number_to_currency(product.price)
]
end
end

def products
@products ||= fetch_products
end

def fetch_products
products = Product.order("#{sort_column} #{sort_direction}")
products = products.page(page).per_page(per_page)
if params[:sSearch].present?
products = products.where("name like :search or category like :search", search: "%#{params[:sSearch]}%")
end
products
end

def page
params[:iDisplayStart].to_i/per_page + 1
end

def per_page
params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10
end

def sort_column
columns = %w[name category released_on price]
columns[params[:iSortCol_0].to_i]
end

def sort_direction
params[:sSortDir_0] == "desc" ? "desc" : "asc"
end
end
[/ruby]

Screencast: Private Pub für Realtime-Events

Privat Pub ist ein Gem mit dem Echtzeit-Events auf sehr einfach Weise erstellt und genutzt werden können. In diesem Screencast erfahrt ihr wie es in Kombination mit Rails verwendet werden kann.

 

Downloads in verschiedenen Formaten:

mp4
mp4
webm
ogg

 

Resourcen:

Gemfile

[ruby]
gem ‚private_pub‘
[/ruby]

terminal

[bash]
bundle
rails g private_pub:install
rackup private_pub.ru -s thin -E production
[/bash]

messages/index.html.erb

[html]
<%= subscribe_to "/messages/new" %>
[/html]

messages/create.js.erb

[javascript]
<% publish_to "/messages/new" do %>
$("#chat").append("<%= j render(@message) %>");
<% end %>
[/javascript]

messages_controller.rb

[ruby]
PrivatePub.publish_to("/messages/new", message: @message)
[/ruby]

app/assets/javascripts/messages.js.coffee

[javascript]
PrivatePub.subscribe "/messages/new", (data, channel) ->
alert data.message.content
[/javascript]

Screencast: Im Browser „In-Place“ Editieren

In-Place Editing bezeichnet die Möglichkeit im Browser direkt Bereiche zu bearbeiten. Diese Funktion wird gerne CMS Systemen verwendet um den Anwender eine einfache Möglichkeit zu bieten um Inhalte ohne Umwege zu verändern und/oder zu erstellen. Ryan zeigt in diesem Screencast wie dies umgesetzt werden kann.

 

Downloads in verschiedenen Formaten:

mp4
m4v
webm
ogg

 

Resourcen:

Gemfile

[ruby]
gem ‚best_in_place‘
[/ruby]

app/assets/javascripts/application.js

[javascript]
//= require jquery.purr
//= require best_in_place
[/javascript]

app/assets/javascripts/users.js.coffee

[javascript]
jQuery ->
$(‚.best_in_place‘).best_in_place()
[/javascript]

users/show.html.erb

[html]
<p>
<b>Name:</b>
<%= best_in_place @user, :name %>
</p>
<p>
<b>Email:</b>
<%= best_in_place @user, :email %>
</p>
<p>
<b>Gender:</b>
<%= best_in_place @user, :gender, type: :select, collection: [["Male", "Male"], ["Female", "Female"], ["", "Unspecified"]] %>
</p>
<p>
<b>Public profile:</b>
<%= best_in_place @user, :public_profile, type: :checkbox, collection: %w[No Yes] %>
</p>
<p>
<%= best_in_place @user, :bio, type: :textarea %>
</p>
[/html]

users_controller.rb

[ruby]
respond_to :html, :json
def update
@user = User.find(params[:id])
@user.update_attributes(params[:user])
respond_with @user
end
[/ruby]

app/assets/stylesheets/users.css.scss

[css]
.purr {
position: fixed;
top: 30px;
right: 100px;
width: 250px;
padding: 20px;
background-color: #FCC;
border: solid 2px #C66;
&:first-letter { text-transform: uppercase; }
}
[/css]

Screencast: Mit PJAX Bereiche aktualisieren

Häfig wird bei kleinsten Änderungen in Teilbereichen einer Seite die gesamte Seite erneut gerendert. Die führt zu „unnötigen“ Seiten-Generierungen die gespart werden können. PJAX kann neue oder aktualisierte Bereiche über AJAX holen und somit die Seite stets aktuell halten. Ryan zeigt diese Woche wie es eingesetzt werden kann.

 

Downloads in verschiedenen Formaten:

mp4
m4v
webm
ogg

 

Resourcen:

Gemfile

[ruby]
gem ‚pjax_rails‘
[/ruby]

app/assets/javascripts/application.js

[javascript]
//= require jquery.pjax
[/javascript]

layouts/application.html.erb

[html]
<div data-pjax-container>
<%= yield %>
</div>
[/html]

index.html.erb

[html]
<title><%= yield(:title) %></div>
[/html]

Gemfile

[ruby]
gem ‚rack-pjax‘
[/ruby]

config/application.rb

[ruby]
config.middleware.use Rack::Pjax
[/ruby]

bash

[bash]
mkdir -p vendor/assets/javascripts
curl https://raw.github.com/defunkt/jquery-pjax/master/jquery.pjax.js > vendor/assets/javascripts/jquery.pjax.js
[/bash]

app/assets/javascripts/application.js

[javascript]
//= require jquery.pjax
[/javascript]

products.js.coffee

[javascript]
jQuery ->
$(‚.product a‘).pjax(‚[data-pjax-container]‘)
[/javascript]

index.html.erb

[html]
<div data-pjax-container>

</div>
[/html]

Screencast: jQuery Tokeninput

Autokompletierung ist eine hilfreiche Funktion für viele Anwender. Mit jQuery Tokeninput ist die relativ einfach umzusetzen. Ryan zeigt zudem noch wie es im Zusammenhang mit Rails eingesetzt werden kann.

 

Download:

Download(21.7 MB, 11:09)
Alternativer Download für iPod & Apple TV(20.4 MB, 11:09)

 

Resourcen:

 

Quellcode:

[bash]
bundle
rails g jquery:install
[/bash]

[ruby]
# Gemfile
gem "jquery-rails"

# models/book.rb
class Book < ActiveRecord::Base
attr_accessible :name, :author_tokens
has_many :authorships
has_many :authors, :through => :authorships
attr_reader :author_tokens

def author_tokens=(ids)
self.author_ids = ids.split(",")
end
end

# authors_controller.rb
def index
@authors = Author.where("name like ?", "%#{params[:q]}%")
respond_to do |format|
format.html
format.json { render :json => @authors.map(&:attributes) }
end
end
[/ruby]

[html]
<!– layouts/application.html.erb –>
<%= stylesheet_link_tag "application", "token-input-facebook" %>
<%= javascript_include_tag :defaults, "jquery.tokeninput" %>

<!– books/_form.html.erb –>
<p>
<%= f.label :author_tokens, "Authors" %><br />
<%= f.text_field :author_tokens, "data-pre" => @book.authors.map(&:attributes).to_json %>
</p>
[/html]

[javascript]
// application.js
$(function() {
$("#book_author_tokens").tokenInput("/authors.json", {
crossDomain: false,
prePopulate: $("#book_author_tokens").data("pre"),
theme: "facebook"
});
});
[/javascript]

Screencast: Ajax Historie anpassen

Die neue pushState Funktion in JavaScript erlaubt es die gesamte URL mit Ajax zu verändern bzw. an den eigenen Bedarf anzupassen. Das bedeutet das auf einfache Weise eine Unterstützung für die Buttons „Zurück“, „Neu Laden“ und „Lesezeichen“ implementiert werden kann. Ryan zeigt in diesem Screencast wie dies in Kombination mit Rails eingesetzt werden kann.

 

Download:

Download(19.9 MB, 10:35)
Alternativer Download für iPod & Apple TV(18.9 MB, 10:35)

 

Resourcen:

 

Quellcode:

[javascript]
/* application.js */
if (history && history.pushState) {
$(function() {
$("#products th a, #products .pagination a").live("click", function() {
$.getScript(this.href);
history.pushState(null, document.title, this.href);
return false;
});
$("#products_search input").keyup(function() {
$.get($("#products_search").attr("action"), $("#products_search").serialize(), null, "script");
history.replaceState(null, document.title, $("#products_search").attr("action") + "?" + $("#products_search").serialize());
return false;
});
$(window).bind("popstate", function() {
$.getScript(location.href);
});
});
}

/* products/index.js.erb */
$("#products").html("<%= escape_javascript(render("products")) %>");
document.title = "<%= escape_javascript("#{params[:search].to_s.titleize} Products by #{(params[:sort] || ’name‘).titleize} – Page #{params[:page] || 1}") %>";
[/javascript]

Screencast: Suchen, Sortieren, Pagination mit AJAX

Viele Administrationsseiten bieten die Möglichkeite zu Suchen, Sortieren oder Daten seitenweise anzuzeigen. In dieser Woche zeigt Ryan wie diese Funktionen mit AJAX umgesetzt werden können.

 

Download:

Download(20.7 MB, 13:43)
Alternativer Download für iPod & Apple TV(19.9 MB, 13:43)

 

Resourcen:

 

Quellcode:

[bash]
rails g jquery:install
[/bash]

[ruby]
# Gemfile
gem ‚will_paginate‘, ‚3.0.pre2‘
gem ‚jquery-rails‘

# products_controller.rb
def index
@products = Product.search(params[:search]).order(sort_column + " " + sort_direction).paginate(:per_page => 5, :page => params[:page])
end

# models/product.rb
def self.search(search)
if search
where(’name LIKE ?‘, "%#{search}%")
else
scoped
end
end

# helpers/application_helper.rb
def sortable(column, title = nil)
title ||= column.titleize
css_class = column == sort_column ? "current #{sort_direction}" : nil
direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
link_to title, params.merge(:sort => column, :direction => direction, :page => nil), {:class => css_class}
end
[/ruby]

[html]
<!– products/index.html.erb –>
<%= form_tag products_path, :method => ‚get‘, :id => "products_search" do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<div id="products"><%= render ‚products‘ %></div>
<% end %>

<!– products/_products.html.erb –>
<%= hidden_field_tag :direction, params[:direction] %>
<%= hidden_field_tag :sort, params[:sort] %>
<%= will_paginate @products %>

<!– products/index.js.erb –>
$("#products").html("<%= escape_javascript(render("products")) %>");
[/html]

Screencast: Polling nach Aktualisierungen

Bei häufig aktualisierten Daten auf der Serverseite, ist es hilfreich diese dem Benutzer automatisch anzuzeigen. In diesem Screencast zeigt Ryan wie dies mit JQuery gelöst werden kann.

 

Download:

Download(23.2 MB, 16:07)
Alternativer Download für iPod & Apple TV(22.3 MB, 16:07)

 

Resourcen:

 

Quellcode:

[bash]
bundle install
rails g jquery:install
[/bash]

[ruby]
# Gemfile
gem ‚jquery-rails‘

# comments_controller.rb
def index
@comments = Comment.where("article_id = ? and created_at > ?", params[:article_id], Time.at(params[:after].to_i + 1))
end
[/ruby]

[html]
<!– layouts/application.html.erb –>
<%= javascript_include_tag :defaults %>
<%= csrf_meta_tag %>

<!– articles/show.html.erb –>
<div id="article" data-id="<%= @article.id %>">

<div class="comment" data-time="<%= comment.created_at.to_i %>">

<!– comments/index.js.erb –>
<% unless @comments.empty? %>
$("#comments").append("<%=raw escape_javascript(render(@comments)) %>");
$("#article h2").text($(".comment").length + " comments");
<% end %>
[/html]

Screencast: Unobtrusive Javascript in Rails 3

Wie in den Vorgängerversionen unterstützt auch Rails 3 bei der Integration von JavaScript. Ryan zeigt diese Woche welche Möglichkeiten Rails 3 bietet.

 

Download:

Download (27.4 MB, 13:18)
Alternativer Download für iPod & Apple TV (17.7 MB, 13:18)

 

Resourcen:

 

Quellcode:

[html]
<!– ujs_example.html –>
<!DOCTYPE html>
<html>
<head>
<title>UJS Example</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
$(function() {
$("#alert").click(function() {
alert(this.getAttribute("data-message"));
return false;
})
})
</script>
</head>
<body>
<h1><a href="#" id="alert" data-message="Hello UJS!">Click Here</a></h1>
</body>
</html>

<!– layouts/application.html.erb –>
<%= javascript_include_tag :defaults %>
<!– or –>
<%= javascript_include_tag "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js", "jquery.rails.js" %>
<%= csrf_meta_tag %>

<!– products/index.html.erb –>
<% form_tag products_path, :method => :get, :remote => true do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>

<div id="products">
<%= render @products %>
</div>
[/html]

[html]
// products/index.js.erb
$("products").update("<%= escape_javascript(render(@products)) %>");
// or
$("#products").html("<%= escape_javascript(render(@products)) %>");
[/html]

Prototype and script.aculo.us. You Never Knew JavaScript Could Do This! (Pragmatic Programmers)

Web applications are getting richer and richer, with more interaction baked in every day. But JavaScript, DOM, CSS and a full host of other Web standards are quite complex, and the result isn’t always browser compliant. The Prototype and script.aculo.us libraries are veritable treasure troves, smoothing over all the usual nitty-gritty differences between browsers, and making most common features a breeze to implement.

With this book, you can quickly wield the whole power of these extraordinary libraries. You can dive into Prototype, the library that makes JavaScript so much more powerful, and it looks a lot like Ruby code.Exploring the DOM, handling events, taming AJAX, and radically simplifying most of your scripting code: it all becomes easy – and very portable – with Prototype. When it comes to advanced UI features, script.aculo.us is every web developer’s dream come true: whether you need to create auto-completed text inputs, implement in-place editors, provide customized drag-and-drop behaviors, capture your users‘ attention with visual effects or simply build DOM fragments more efficiently, it’s all there, and lightweight too.

This book guides you through all the details of these features, letting you use many technologies on the server side, such as PHP, vanilla Ruby, and Ruby On Rails, in countless examples illustrating every aspect. Power users will also learn the design philosophies of the libraries, and how to contribute to them and augment them for their own needs.

  • Taschenbuch: 436 Seiten
  • Verlag: (2008-01-25 )
  • Preis: 18.44 €
  • Sprache: english
  • ISBN-10: 1934356018
  • Autor(en): Christophe Porteneuve
  • kaufen