Skip to content

Instantly share code, notes, and snippets.

@xenda
Created January 12, 2010 23:53
Show Gist options
  • Save xenda/275771 to your computer and use it in GitHub Desktop.
Save xenda/275771 to your computer and use it in GitHub Desktop.
Some Code Samples
class PostsController < InheritedResources::Base
belongs_to :blog, :optional => true
before_filter :admin_or_owner_only, :only => [:create,:new,:update,:edit,:destroy]
after_filter :register_post_visit, :only =>[:show,:index]
before_filter :register_brain_buster, :only => [:show]
def register_brain_buster
create_brain_buster unless current_user
end
def new
setup_post
@post = @blog.posts.build
session[:current_post_id] = @post.id
new!
end
def edit
setup_post
@post = Post.find_by_permalink(params[:id])
session[:current_post_id] = @post.id
edit!
end
def index
redirect_to blog_permalink_path(params[:blog_id])
end
def create
@post = Post.new(params[:post])
@post.user = current_user
@post.published_date ||= Time.zone.now
@post.drafted_date ||= Time.zone.now
@post.blog_id = params[:blog_id]
update_status
session[:current_post_id] = nil
create! do |success,failure|
success.html{ redirect_to blog_post_path(@post.blog.permalink,@post.permalink) }
failure.html { setup_post; render :action=>"new" }
end
end
def update
@post = Post.find(params[:id])
update_status
session[:current_post_id] = nil
update! do |success,failure|
success.html{ redirect_to blog_post_path(@post.blog.permalink,@post.permalink) }
failure.html { setup_post; render :action=>"edit" }
end
end
def show
@post = Post.find_by_permalink(params[:id])
@blog = @post.blog
@comment = Comment.new
if current_user
@comment.user_id = current_user.id
@comment.name = current_user.name
@comment.email = current_user.email
end
show!
end
protected
def setup_post
@blog = Blog.find_by_permalink(params[:blog_id])#current_user.blog
@blog_image = @blog.blog_images.build
@category = Category.new
@category.user = current_user
@categories = current_user.categories
end
def update_status
if params[:commit] == "publicar"
@post.mark_as_published
elsif params[:commit] == "grabar" or params[:commit] == "a borrador"
@post.mark_as_drafted
end
end
def collection
@posts ||= end_of_association_chain.paginate :page => params[:page], :per_page => (params[:per_page] || 20)
end
end
# == Schema Information
#
# Table name: posts
#
# id :integer(4) not null, primary key
# title :string(255)
# content :text
# category_id :integer(4)
# user_id :integer(4)
# permalink :string(255)
# created_at :datetime
# updated_at :datetime
# blog_id :integer(4)
# drafted_date :datetime
# published_date :datetime
# cached_tag_list :string(255)
# comments_count :integer(4)
# reviewed_date :datetime
# delta :boolean(1) default(TRUE), not null
# status :string(255)
#
class Post < ActiveRecord::Base
attr_accessible :title, :content, :category_id, :user_id, :permalink, :blog_id, :tag_list, :drafted_date, :published_date, :category_ids,:reviewed_date
has_many :comments, :order=>"created_at ASC"
belongs_to :blog, :counter_cache=>true
has_many :post_categories
has_many :categories, :through => :post_categories
has_many :tracks
belongs_to :user
validates_presence_of :title,:user_id,:permalink, :on => :create, :message => "can't be blank"
has_permalink :title, :update => true,:if => Proc.new {|post| post.nil? or post.permalink.blank? }
POST_TYPES = [ 'drafted','reviewed','published']
named_scope :draft, :conditions=>{:status=>POST_TYPES[0]}, :order=>"drafted_date DESC"
named_scope :published, :conditions=>{:status=>POST_TYPES[2]}, :order=>"published_date DESC"
named_scope :reviewed, :conditions=>{:status=>POST_TYPES[1]}, :order=>"reviewed_date DESC"
named_scope :last_published, lambda {|limit| {:order => "published_date DESC", :conditions=>{:status=>"published"}, :limit => limit} }
named_scope :next_from, lambda {|limit,offset| {:order => "published_date DESC", :limit => limit, :offset => offset} }
named_scope :from_category, lambda {|category_id| {:conditions=>{:category_id=>category_id} } }
named_scope :from_named_category, lambda {|category_permalink| {:joins=>{:post_categories=>:category}, :conditions=>{:post_categories=>{:categories=>{:permalink=>category_permalink}}}} }
named_scope :from_blog_named, lambda{|category_name| {:joins=>{:blog=>:category}, :conditions=>{:blog=>{:categories=>{:permalink=>category_name}}}} }
named_scope :active, :joins=>:blog, :conditions=>"blogs.active is true or blogs.active is null"
named_scope :published_from_each_blog, :joins=>:blog, :conditions => "posts.published_date = (SELECT MAX(ps.published_date) FROM `posts` ps WHERE ps.blog_id = posts.blog_id and status like 'published') and blogs.active is true", :order=>"published_date DESC"
#TODO
named_scope :most_read, :joins=>"LEFT JOIN tracks t on t.post_id = posts.permalink", :select=>"count(post_id) as count, posts.title, posts.blog_id, posts.permalink, posts.created_at", :group=>"post_id", :order=>"count DESC", :limit=>8
named_scope :most_commented, :limit=>8, :order=>"comments_count DESC, published_date DESC"
#TODO
named_scope :most_voted, :limit=>8, :order=>"published_date DESC"
EXCERPT_SIZE = 40
acts_as_taggable
define_index do
indexes title, :sortable => true
indexes content
indexes permalink, :sortable => true
indexes user(:name), :as => :author, :sortable => true
#indexes category(:name), as => :category_name
indexes cached_tag_list
has user_id, created_at, updated_at, blog_id, category_id
set_property :delta => true
#TODO: Filter by published where "status = 'published'"
end
def total_visits
Track.count(:conditions=>{:post_id=>self.permalink})
end
def mark_as_drafted
self.status = POST_TYPES[0]
self.drafted_date = Time.zone.now
self.save
end
def mark_as_reviewed
self.status = POST_TYPES[1]
self.reviewed_date = Time.zone.now
self.save
end
def mark_as_published
self.status = POST_TYPES[2]
self.published_date = Time.zone.now
self.save
end
def published?
self.status == POST_TYPES[2]
end
def drafted?
self.status == POST_TYPES[0]
end
def category_name
return "" if self.category.blank?
self.category.name
end
def category_names
return "" if self.categories.blank?
self.categories.map(&:name).join(",")
end
def self.update_all_author
Post.all.each do |p|
p.user_id = p.blog.user_id
p.save
end
end
def word_count
content.split(/\s/).size
end
def tag_names
return "" if self.tags.empty?
self.tags.map(&:name).join(",")
end
def self.aggregate_all_visits
Post.suspended_delta do
Post.find_each do |p|
p.visits_count = total_visits
end
end
end
end
- content_for :javascript do
=javascript_include_tag 'tiny_mce/tiny_mce','editor_loader','swfobject','swfupload','swfupload.queue','jquery.swfupload','jquery.jcarousel'
- semantic_form_for [@post.blog,@post] do |form|
= form.error_messages
- form.inputs do
#main_post_content
= form.input :title, :label => "T&iacute;tulo"
= form.input :content, :label => "&nbsp;"
#additional_post_content
.side_fields{:style=>"display:none;"}
= link_to "Agregar im&aacute;genes", "#fancybox_images", {:class=>"open-inline large"}
.side_fields
=render :partial=>"user_categories"
= link_to "Agregar categor&iacute;a","#category_add",{:class=>"open-inline"}
.side_fields
= form.input :tag_list, :label => "Etiquetas", :id=>"tag_list_field",:hint=>"separados por comas"
.side_fields
= form.input :published_date,:as=>:date,:label => "Fecha de Publicaci&oacute;n", :id=>"published_date_field"
.side_buttons
- form.buttons do
= form.commit_button "publicar", :button_html => { :id=>"publish_button", :class=>"submit"}
- if @post.published?
= form.commit_button "a borrador", :button_html => { :id=>"draft_button", :class=>"submit" }
- else
= form.commit_button "guardar", :button_html => { :id=>"draft_button", :class=>"submit" }
= link_to "cancelar", blog_path(@post.blog.permalink)
#category_add{:style=>"display:none;"}
%h3 A&ntilde;adiendo una categor&iacute;a al blog
-remote_form_for @category do |f|
= f.label "Nombre de la categor&iacute;a:"
= f.hidden_field :user_id
= f.text_field :name
= f.submit "Grabar"
#fancybox_images{:style=>"display:none;"}
#upload_images_container
#upload_images_sources
#actual_images_pagination.image_source
%h3 Elija la imagen del archivo:
.image_source_content=render :partial => "/posts/display_owned_images"
= error_messages_for :blog_image
- remote_form_for @blog_image, :html => { :multipart => true } do |f|
#internet_image.image_source
%h3 O agregue una desde Internet (pegar URL):
.image_source_content
= f.text_field :image_url
= f.hidden_field :blog_id
= f.submit "Agregar", :disable_with => "Agregando...", :id=>"submit_url"
#upload_image.image_source
%h3 o adjunte una de su computadora:
.image_source_content
#swfupload-control
%p Puede enviar hasta 5 im&aacute;genes de su PC con un tama&ntilde;o m&aacute;ximo de 1mb cada uno (png,jpg,gif).
%input{ :type=>"button", :id=>"upload_button", :class=>"fancy_upload_button"}
%p#queuestatus
%ol#log
- content_for :javascript do
:javascript
var token = '/fotos_blog?' + encodeURI('#{session_information}');
#upload_images_actions
.selected_text
Seleccionada:
#selected_image Ninguna
.image_actions
%h3 Tama&ntilde;o:
%ul#uploaded_image_sizes
%li
=radio_button_tag('size', "thumbnail")
=label_tag 'thumbnail', 'Miniatura'
%li
=radio_button_tag('size',"small")
=label_tag 'small', 'Peque&ntilde;a'
%li
=radio_button_tag('size', "median")
=label_tag 'median', 'Mediana'
%li
=radio_button_tag('size', "large")
=label_tag 'large', 'Grande'
%li
=radio_button_tag('size', "original", {:selected=>true})
=label_tag 'original', 'Original'
.image_actions
%h3 Enlazado a:
%ul#link_actions
%li
=radio_button_tag('image_action',"none", {:selected=>true})
=label_tag 'thumbnail', 'sin enlace'
%li
=radio_button_tag('image_action',"Enlazado a ")
=text_field_tag( 'url' )
%li
=radio_button_tag('image_action',"to_original")
=label_tag 'thumbnail', 'a Imagen Original'
= submit_tag "Agregar imagen", :class=>"insert_image"
= link_to "Cancelar", "#", {:class=>"close_fancybox"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment