Screencast: Einführung in Draper

 

Downloads in verschiedenen Formaten:

mp4
m4v
webm
ogg

 

Resourcen:

bash

rails g draper:decorator user

Gemfile

gem 'draper'

app/decorators/user_decorator.rb

class UserDecorator < ApplicationDecorator
  decorates :user
  allows :username
  
  def avatar
    site_link h.image_tag("avatars/#{avatar_name}", class: "avatar")
  end
  
  def linked_name
    site_link(model.full_name.present? ? model.full_name : model.username)
  end
  
  def website
    handle_none model.url do
      h.link_to model.url, model.url
    end
  end
  
  def twitter
    handle_none model.twitter_name do
      h.link_to model.twitter_name, "http://twitter.com/#{model.twitter_name}"
    end
  end
  
  def bio
    handle_none model.bio do
      markdown(model.bio)
    end
  end
  
  def member_since
    model.created_at.strftime("%B %e, %Y")
  end
  
private
  
  def handle_none(value)
    if value.present?
      yield
    else
      h.content_tag :span, "None given", class: "none"
    end
  end
  
  def site_link(content)
    h.link_to_if model.url.present?, content, model.url
  end

  def avatar_name
    if model.avatar_image_name.present?
      model.avatar_image_name
    else
      "default.png"
    end
  end
end

app/decorators/application_decorator.rb

class ApplicationDecorator < Draper::Base
  def markdown(text)
    Redcarpet.new(text, :hard_wrap, :filter_html, :autolink).to_html.html_safe
  end
end

app/controllers/users_controller.rb

def show
  @user = UserDecorator.find(params[:id])
end

users/show.html.erb

<div id="profile">
  <%= @user.avatar %>
  <h1><%= @user.linked_name %></h1>
  <dl>
    <dt>Username:</dt>
    <dd><%= @user.username %></dd>
    <dt>Member Since:</dt>
    <dd><%= @user.member_since %></dd>
    <dt>Website:</dt>
    <dd><%= @user.website %></dd>
    <dt>Twitter:</dt>
    <dd><%= @user.twitter %></dd>
    <dt>Bio:</dt>
    <dd><%= @user.bio %></dd>
  </dl>
</div>

Hinterlasse eine Antwort

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind markiert *

Du kannst folgende HTML-Tags benutzen: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>