Skip to content

Instantly share code, notes, and snippets.

@jeffrydegrande
Created October 17, 2010 11:05
Show Gist options
  • Save jeffrydegrande/630754 to your computer and use it in GitHub Desktop.
Save jeffrydegrande/630754 to your computer and use it in GitHub Desktop.
class Post < ActiveRecord::Base
attr_accessible :title, :body
acts_as_commentable
# validations
belongs_to :author, :class_name => 'User', :foreign_key => 'user_id'
validates_presence_of :body
scope :with_title, :conditions => [ "title IS NOT NULL" ]
scope :recent, lambda { |limit| {:limit => limit || 30, :order => 'created_at DESC'}}
# callbacks
fires :new_post, :on => :create, :actor => :author
before_save :store_rendered_copy
def store_rendered_copy
if self.body_changed?
self.rendered_body = render!
end
true
end
def to_s
title || "este recado"
end
def body
self.rendered_body ||= render!
end
private
def render!
raw = read_attribute(:body)
if raw.present?
embedded = Post.transform(raw)
markdown = RDiscount.new(embedded)
rendered_body = markdown.to_html
end
end
def self.transform(txt, *attrs, &block)
ret = txt.dup
extract_links!(txt) do |u|
transform_url_for_text!(u, ret, *attrs, &block)
end
ret
end
def self.transform_url_for_text!(u, txt, *attrs, &block)
begin
oembed = OhEmbedr::OhEmbedr.new(:url => u, *attrs)
response = oembed.gets['html']
txt.gsub!(u, response) if response.present?
rescue OhEmbedr::Error => error
# don't touch the string
end
end
def self.extract_links!(s, &block)
reg = /(https?:\/\/[^\s]+)/i
if block_given?
s.scan(reg) { yield $& }
nil
else
result = []
str.scan(reg) { result.push $& }
result
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment