Screencast: Bildbearbeitung mit RMagick

In diesem Screencast zeigt Ryan wie Bilder mit RMagick verändert und/oder verarbeitet werden. Teil des Screencastes widmet er auch CarrierWave das in Kombination mit RMagick für die Verarbeitung von hochgeladenen Bildern eingesetzt werden kann.

Downloads in verschiedenen Formaten:

mp4
m4v
webm
ogg

 

Resourcen:

terminal

[bash]
brew install imagemagick
convert -version
convert octocat.png -resize ’70×70^‘ -gravity center -crop ’70×70+0+0′ -quantize GRAY -colors 256 -contrast source.png
composite stamp_overlay.png source.png source.png
convert -size 70×70 canvas:red ( octocat.png -resize ’70×70^‘ -gravity center -crop ’70×70+0+0′ -quantize GRAY -colors 256 -contrast stamp_overlay.png -composite -negate ) -compose copy-opacity -composite stamp.png
gem install rmagick
mate stamp.rb
ruby stamp.rb
[/bash]

stamp.rb

[ruby]

require "rmagick"

source = Magick::Image.read("octocat.png").first
source = source.resize_to_fill(70, 70).quantize(256, Magick::GRAYColorspace).contrast(true)
overlay = Magick::Image.read("stamp_overlay.png").first
source.composite!(overlay, 0, 0, Magick::OverCompositeOp)
colored = Magick::Image.new(70, 70) { self.background_color = "red" }
colored.composite!(source.negate, 0, 0, Magick::CopyOpacityCompositeOp)
colored.write("stamp.png")

# Or through the command line:
# system <<-COMMAND
# convert -size 70×70 canvas:red \( octocat.png
# -resize ’70×70^‘ -gravity center -crop ’70×70+0+0′
# -quantize GRAY -colors 256 -contrast stamp_overlay.png
# -composite -negate
# \) -compose copy-opacity -composite stamp.png
# COMMAND
[/ruby]

Gemfile

[ruby]
gem ‚rmagick‘
gem ‚carrierwave‘
[/ruby]

models/stamp.rb

[ruby]

mount_uploader :image, StampUploader
[/ruby]

app/uploaders/stamp_uploader.rb

[ruby]

class StampUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick

# Include the Sprockets helpers for Rails 3.1+ asset pipeline compatibility:
include Sprockets::Helpers::RailsHelper
include Sprockets::Helpers::IsolatedHelper

# Choose what kind of storage to use for this uploader:
storage :file

# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end

# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
def extension_white_list
%w(jpg jpeg gif png)
end

%w[red green blue purple black].each do |color|
version(color) { process stamp: color }
end

def stamp(color)
manipulate! format: "png" do |source|
overlay_path = Rails.root.join("app/assets/images/stamp_overlay.png")
overlay = Magick::Image.read(overlay_path).first
source = source.resize_to_fill(70, 70).quantize(256, Magick::GRAYColorspace).contrast(true)
source.composite!(overlay, 0, 0, Magick::OverCompositeOp)
colored = Magick::Image.new(70, 70) { self.background_color = color }
colored.composite(source.negate, 0, 0, Magick::CopyOpacityCompositeOp)
end
end
end
[/ruby]

stamps/index.html

[html]
<%= image_tag stamp.image_url(:blue) %>
[/html]

Screencast: Bullet

Bullet ist ein Ruby gem das die abgesetzten SQL Befehle analysiert und beim Endecken von Verbesserungspotial den Anwender auf diese hinweist.
Es unterstützt dabei eine Vielzahl an Benachrichtigungsmöglichkeiten.

 

Downloads in verschiedenen Formaten:

mp4
m4v
webm
ogg

 

Resourcen:

terminal

[bash]
rails g migration add_products_count_to_categories products_count:integer
rails g migration cache_products_count
rake db:migrate
[/bash]

Gemfile

[ruby]

gem ‚bullet‘, group: :development
[/ruby]

config/initializers/bullet.rb

[ruby]

if defined? Bullet
Bullet.enable = true
# Bullet.alert = true
Bullet.bullet_logger = true
end
[/ruby]

categories_controller.rb

[ruby]

def index
@categories = Category.order(:name).includes(:products)
end
[/ruby]

db/migrate/cache_products_count.rb

[ruby]

class CacheProductsCount < ActiveRecord::Migration
def up
execute "update categories set products_count=(select count(*) from products where category_id=categories.id)"
end

def down
end
end
[/ruby]

Screencast: Ransack

Mit Ransack können auf eine Weise komplexe und anspruchsvolle Suchformulare erstellt werden. Es unterstützt auch bei der Darstellung der Suchergebnisse, indem es sortierbare Listen und dynamische Suchseiten erstellt.

 

Downloads in verschiedenen Formaten:

mp4
m4v
webm
ogg

 

Resourcen:

Gemfile

[ruby]

gem ‚ransack‘
[/ruby]

products_controller.rb

[ruby]

def index
@search = Product.search(params[:q])
@products = @search.result
end
[/ruby]

products/index.html.erb

[html]

<%= search_form_for @search, url: search_products_path, method: :post do |f| %>
<%= f.condition_fields do |c| %>
<%= render "condition_fields", f: c %>
<% end %>
<p><%= link_to_add_fields "Add Conditions", f, :condition %></p>
<div class="field">
Sort:
<%= f.sort_fields do |s| %>
<%= s.sort_select %>
<% end %>
</div>
<div class="actions"><%= f.submit "Search" %></div>
<% end %>

<table id="products">
<tr>
<th><%= sort_link @search, :name, "Product Name" %></th>
<th><%= sort_link @search, :released_on, "Release Date" %></th>
<th><%= sort_link @search, :price, "Price" %></th>
</tr>
<% @products.each do |product| %>
<tr>
<td><%= link_to(product.name, product) %></td>
<td><%= product.released_on.strftime("%B %e, %Y") %></td>
<td><%= number_to_currency(product.price) %></td>
</tr>
<% end %>
</table>
[/html]

config/routes.rb

[ruby]

resources :products do
collection { post :search, to: ‚products#index‘ }
end
[/ruby]

products_controller.rb

[ruby]
def index
@search = Product.search(params[:q])
@products = @search.result
@search.build_condition if @search.conditions.empty?
@search.build_sort if @search.sorts.empty?
end
[/ruby]

products/index.html.erb

[html]
<%= search_form_for @search, url: search_products_path, method: :post do |f| %>
<%= f.condition_fields do |c| %>
<%= render "condition_fields", f: c %>
<% end %>
<p><%= link_to_add_fields "Add Conditions", f, :condition %></p>
<div class="field">
Sort:
<%= f.sort_fields do |s| %>
<%= s.sort_select %>
<% end %>
</div>
<div class="actions"><%= f.submit "Search" %></div>
<% end %>
[/html]

products/_condition_fields.html.erb

[html]

<div class="field">
<%= f.attribute_fields do |a| %>
<%= a.attribute_select associations: [:category] %>
<% end %>
<%= f.predicate_select %>
<%= f.value_fields do |v| %>
<%= v.text_field :value %>
<% end %>
<%= link_to "remove", ‚#‘, class: "remove_fields" %>
</div>
[/html]

application_helper.rb

[ruby]

def link_to_add_fields(name, f, type)
new_object = f.object.send "build_#{type}"
id = "new_#{type}"
fields = f.send("#{type}_fields", new_object, child_index: id) do |builder|
render(type.to_s + "_fields", f: builder)
end
link_to(name, ‚#‘, class: "add_fields", data: {id: id, fields: fields.gsub("n", "")})
end
[/ruby]

products.js.coffee

[javascript]
jQuery ->
$(‚form‘).on ‚click‘, ‚.remove_fields‘, (event) ->
$(this).closest(‚.field‘).remove()
event.preventDefault()

$(‚form‘).on ‚click‘, ‚.add_fields‘, (event) ->
time = new Date().getTime()
regexp = new RegExp($(this).data(‚id‘), ‚g‘)
$(this).before($(this).data(‚fields‘).replace(regexp, time))
event.preventDefault()
[/javascript]

Screencast: MiniProfiler

MiniProfiler erlaubt es sich Geschwindigkeitsmessungen direkt auf der aufgerufenen Seite anzuschauen. Dabei werden auch die aufgerufenen SQL Befehle und wenn gewünscht Messungen für ausgesuchte Code-Blöcke.

 

Downloads in verschiedenen Formaten:

mp4
m4v
webm
ogg

 

Resourcen:

Gemfile

[ruby]

gem ‚rack-mini-profiler‘
[/ruby]

products/index.html.erb

[html]
<%= pluralize project.tasks.size, "task" %>
[/html]

projects_controller.rb

[ruby]

@projects = Project.order(:created_at).select("projects.*, count(tasks.id) as tasks_count").joins("left outer join tasks on project_id=projects.id").group("projects.id")
Rack::MiniProfiler.step("fetch projects") do
@projects.all
end
[/ruby]

config/environments/production.rb

[ruby]

config.serve_static_assets = true
[/ruby]

terminal

[bash]
rake assets:precompile
rake db:setup RAILS_ENV=production
rails s -e production
[/bash]

application_controller.rb

[ruby]

before_filter :miniprofiler

private

def miniprofiler
Rack::MiniProfiler.authorize_request # if user.admin?
end
[/ruby]

Screencast: Sidekiq

Sidekiq erlaubt es Prozesse im Hintergrund asynchron weiter zu verarbeiten während die Applikation bereits neue Anfragen entgegen nehmen kann. Es verwendet dabei Threads anstatt Forks und geht dadurch effizienter mit Resourcen um als vergleichsweise Resque.

 

Downloads in verschiedenen Formaten:

mp4
m4v
webm
ogg

 

Resourcen:

terminal

[bash]

brew install redis
redis-server /usr/local/etc/redis.conf
bundle exec sidekiq
bundle exec sidekiq -q high,5 default
[/bash]

Gemfile

[ruby]
gem ’sidekiq‘
gem ’sinatra‘, require: false
gem ’slim‘
[/ruby]

snippets_controller.rb

[ruby]
PygmentsWorker.perform_async(@snippet.id)
# PygmentsWorker.perform_in(1.hour, @snippet.id)
[/ruby]

app/workers/pygments_worker.rb

[ruby]

class PygmentsWorker
include Sidekiq::Worker
sidekiq_options queue: "high"
# sidekiq_options retry: false

def perform(snippet_id)
snippet = Snippet.find(snippet_id)
uri = URI.parse("http://pygments.appspot.com/")
request = Net::HTTP.post_form(uri, lang: snippet.language, code: snippet.plain_code)
snippet.update_attribute(:highlighted_code, request.body)
end
end
[/ruby]

routes.rb

[ruby]

require ’sidekiq/web‘
# …
mount Sidekiq::Web, at: ‚/sidekiq‘
[/ruby]

Screencast: Active Records Reputation System

Wenn der Durchschnittswert für ein Bewertungssystem oder die Summe von abgegebenen Stimmen berechnet werden müssen, dann lohnt sich ein Blick auf das activerecord-reputation-system gem. Ryan zeigt in diesem Screencast wie es verwendet wird und wie eine selbsterstellte Basis-Version gebaut werden kann.

 

Downloads in verschiedenen Formaten:

mp4
m4v
webm
ogg

 

Resourcen:

terminal

[bash]

rails g reputation_system
rake db:migrate
[/bash]

Gemfile

[ruby]

gem ‚activerecord-reputation-system‘, require: ‚reputation_system‘
[/ruby]

models/haiku.rb

[ruby]

has_reputation :votes, source: :user, aggregated_by: :sum
[/ruby]

models/user.rb

[ruby]

has_many :evaluations, class_name: "RSEvaluation", as: :source

has_reputation :votes, source: {reputation: :votes, of: :haikus}, aggregated_by: :sum

def voted_for?(haiku)
evaluations.where(target_type: haiku.class, target_id: haiku.id).present?
end
[/ruby]

config/routes.rb

[ruby]

resources :haikus do
member { post :vote }
end
[/ruby]

haikus_controller.rb

[ruby]

def index
@haikus = Haiku.find_with_reputation(:votes, :all, order: "votes desc")
end

def vote
value = params[:type] == "up" ? 1 : -1
@haiku = Haiku.find(params[:id])
@haiku.add_or_update_evaluation(:votes, value, current_user)
redirect_to :back, notice: "Thank you for voting"
end
[/ruby]

_haiku.html.erb

[html]

| <%= pluralize haiku.reputation_value_for(:votes).to_i, "vote" %>
<% if current_user && !current_user.voted_for?(haiku) %>
| <%= link_to "up", vote_haiku_path(haiku, type: "up"), method: "post" %>
| <%= link_to "down", vote_haiku_path(haiku, type: "down"), method: "post" %>
<% end %>
[/html]

application.html.erb

[html]

<%= current_user.reputation_value_for(:votes).to_i %>
[/html]

models/haiku_vote.rb

[ruby]

validates_uniqueness_of :haiku_id, scope: :user_id
validates_inclusion_of :value, in: [1, -1]
validate :ensure_not_author

def ensure_not_author
errors.add :user_id, "is the author of the haiku" if haiku.user_id == user_id
end
[/ruby]

models/haiku.rb

[ruby]

def self.by_votes
select(‚haikus.*, coalesce(value, 0) as votes‘).
joins(‚left join haiku_votes on haiku_id=haikus.id‘).
order(‚votes desc‘)
end

def votes
read_attribute(:votes) || haiku_votes.sum(:value)
end
[/ruby]

models/user.rb

[ruby]

def total_votes
HaikuVote.joins(:haiku).where(haikus: {user_id: self.id}).sum(‚value‘)
end

def can_vote_for?(haiku)
haiku_votes.build(value: 1, haiku: haiku).valid?
end
[/ruby]

haikus_controller.rb

[ruby]

def index
@haikus = Haiku.by_votes
end

def vote
vote = current_user.haiku_votes.new(value: params[:value], haiku_id: params[:id])
if vote.save
redirect_to :back, notice: "Thank you for voting."
else
redirect_to :back, alert: "Unable to vote, perhaps you already did."
end
end
[/ruby]

_haiku.html.erb

[html]

| <%= pluralize haiku.votes, "vote" %>
<% if current_user && current_user.can_vote_for?(haiku) %>
| <%= link_to "up", vote_haiku_path(haiku, value: 1), method: "post" %>
| <%= link_to "down", vote_haiku_path(haiku, value: -1), method: "post" %>
<% end %>
[/html]

application.html.erb

[html]

<%= current_user.total_votes %>
[/html]

Screencast: Datenexport nach Excel oder CSV

Für Datenexporte wird häufig CSV und/oder Excel eingesetzt. In Rails ist es relativ einfach diese Formate zur Verfügung zu stellen. Wie dies funktioniert, welche Optionen zur Verfügung stehen und wie ein Excel-Export in verschiedenen Formaten aussehen kann, zeigt Ryan in diesem Screencast.

 

Downloads in verschiedenen Formaten:

mp4
m4v
webm
ogg

 

Resourcen:

config/application.rb

[ruby]
require ‚csv‘
[/ruby]

products_controller.rb

[ruby]
def index
@products = Product.order(:name)
respond_to do |format|
format.html
format.csv { send_data @products.to_csv }
format.xls # { send_data @products.to_csv(col_sep: "t") }
end
end
[/ruby]

models/product.rb

[ruby]
def self.to_csv(options = {})
CSV.generate(options) do |csv|
csv << column_names
all.each do |product|
csv << product.attributes.values_at(*column_names)
end
end
end
[/ruby]

config/initializers/mime_types.rb

[ruby]
Mime::Type.register "application/xls", :xls
[/ruby]

views/products/index.xls.erb

[html]
<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<Worksheet ss:Name="Sheet1">
<Table>
<Row>
<Cell><Data ss:Type="String">ID</Data></Cell>
<Cell><Data ss:Type="String">Name</Data></Cell>
<Cell><Data ss:Type="String">Release Date</Data></Cell>
<Cell><Data ss:Type="String">Price</Data></Cell>
</Row>
<% @products.each do |product| %>
<Row>
<Cell><Data ss:Type="Number"><%= product.id %></Data></Cell>
<Cell><Data ss:Type="String"><%= product.name %></Data></Cell>
<Cell><Data ss:Type="String"><%= product.released_on %></Data></Cell>
<Cell><Data ss:Type="Number"><%= product.price %></Data></Cell>
</Row>
<% end %>
</Table>
</Worksheet>
</Workbook>
[/html]

Screencast: Authentifizierung über Facebook

In diesem Screencast zeigt Ryan wie eine neue Facebook erstellt und konfiguriert werden kann. Zusätzlich zeigt er wie das omniauth-facebook gem eingesetzt wird.

 

Downloads in verschiedenen Formaten:

mp4
m4v
webm
ogg

 

Resourcen:

Gemfile

[ruby]
gem ‚omniauth-facebook‘
[/ruby]

config/initializers/omniauth.rb

[ruby]
OmniAuth.config.logger = Rails.logger

Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, ENV[‚FACEBOOK_APP_ID‘], ENV[‚FACEBOOK_SECRET‘]
end
[/ruby]

terminal

[bash]
rails g model user provider uid name oauth_token oauth_expires_at:datetime
rake db:migrate
[/bash]

models/user.rb

[ruby]
def self.from_omniauth(auth)
where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
user.save!
end
end
[/ruby]

config/routes.rb

[ruby]
match ‚auth/:provider/callback‘, to: ’sessions#create‘
match ‚auth/failure‘, to: redirect(‚/‘)
match ’signout‘, to: ’sessions#destroy‘, as: ’signout‘
[/ruby]

sessions_controller.rb

[ruby]
class SessionsController < ApplicationController
def create
user = User.from_omniauth(env["omniauth.auth"])
session[:user_id] = user.id
redirect_to root_url
end

def destroy
session[:user_id] = nil
redirect_to root_url
end
end
[/ruby]

application_controller.rb

[ruby]
private

def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
[/ruby]

layouts/application.html.erb

[html]
<div id="user_nav">
<% if current_user %>
Signed in as <strong><%= current_user.name %></strong>!
<%= link_to "Sign out", signout_path, id: "sign_out" %>
<% else %>
<%= link_to "Sign in with Facebook", "/auth/facebook", id: "sign_in" %>
<% end %>
</div>
[/html]

app/assets/javascripts/facebook.js.coffee.erb

[javascript]

jQuery ->
$(‚body‘).prepend(‚<div id="fb-root"></div>‘)

$.ajax
url: "#{window.location.protocol}//connect.facebook.net/en_US/all.js"
dataType: ’script‘
cache: true

window.fbAsyncInit = ->
FB.init(appId: ‚<%= ENV["FACEBOOK_APP_ID"] %>‘, cookie: true)

$(‚#sign_in‘).click (e) ->
e.preventDefault()
FB.login (response) ->
window.location = ‚/auth/facebook/callback‘ if response.authResponse

$(‚#sign_out‘).click (e) ->
FB.getLoginStatus (response) ->
FB.logout() if response.authResponse
true
[/javascript]

Screencast: Brakeman

Brakeman ist ein Ruby-Gem mit dem der eigene Ruby-Code innerhalb einer Rails Applikation auf bekannte Sicherheitslücken geprüft werden kann. In diesem Screencast zeigt Ryan wie es eingesetzt werden kann.

 

Downloads in verschiedenen Formaten:

mp4
m4v
webm
ogg

 

Resourcen:

terminal

[bash]
gem install brakeman
rbenv rehash
brakeman
brakeman -o brakeman.html
bundle update rails
brakeman –rake
[/bash]

config/application.rb

[ruby]
config.active_record.whitelist_attributes = true
[/ruby]

products_controller.rb

[ruby]
def index
direction = params[:direction] == "desc" ? "desc" : "asc"
@products = Product.order("name #{direction}")
end
[/ruby]

sessions_controller.rb

[ruby]
redirect_to redirect_url, only_path: true
[/ruby]

models/user.rb

[ruby]
validates_format_of :name, with: /Aw+z/
[/ruby]

Gemfile

[ruby]
gem ‚brakeman‘, group: :development
[/ruby]

Screencast: Session Hijacking

Wenn nach einer Benutzer-Authentifizierung die zugehörigen Cookies über eine unsichere Verbindung ausgetauscht werden, kann dies das Ziel für Session-Hijacking-Angriffe werden. Was in einem solchen Fall getan werden muss und wie dies vermieden werden kann zeigt Ryan in diesem Screencast.

 

Downloads in verschiedenen Formaten:

mp4
m4v
webm
ogg

 

Resourcen:

terminal

[bash]
sudo tcpdump -i lo0 -A
curl http://todo.dev/
curl http://todo.dev/ -H ‚Cookies: …‘
curl https://todo.dev/ -k -H ‚Cookies: …‘
[/bash]

config/environments/production.rb

[ruby]
config.force_ssl = true
[/ruby]

sessions_controller.rb

[ruby]
cookies.signed[:secure_user_id] = {secure: true, value: "secure#{user.id}"}
# …
cookies.delete(:secure_user_id)
[/ruby]

application_controller.rb

[ruby]
def current_user
if !request.ssl? || cookies.signed[:secure_user_id] == "secure#{session[:user_id]}"
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
end
[/ruby]