Sha256: 447851af88d40074344baa859b032da7eaee2bc9405c3a5d7cf5db67e0c41e2f

Contents?: true

Size: 1.96 KB

Versions: 2

Compression:

Stored size: 1.96 KB

Contents

class Post < ActiveRecord::Base
  
  acts_as_taggable

  # for flash messages    
  alias_attribute :name, :title
    
  has_and_belongs_to_many :post_categories
  alias_attribute :categories, :post_categories
  
  has_many :post_products, :dependent => :destroy
  has_many :products, :through => :post_products
  has_many :images, :as => :viewable, :class_name => 'PostImage', :order => :position, :dependent => :destroy
  
  validates :title, :presence => true
  validates :path,  :presence => true, :uniqueness => true, :if => proc{ |record| !record.title.blank? }
  validates :body,  :presence => true
  validates :posted_at, :datetime => true
  
  cattr_reader :per_page
  @@per_page = 10

  scope :live, where(:live => true ).order('posted_at DESC')

 	before_validation :create_path, :if => proc{ |record| record.title_changed? }
  
  
  # Creates date-part accessors for the posted_at timestamp for grouping purposes.
  %w(day month year).each do |method|
    define_method method do
      self.posted_at.send(method)
    end
  end
  	
	def rendered_preview
    preview = body.split("<!-- more -->")[0]
    render(preview)
  end
	
	def rendered_body
	  render(body.gsub("<!-- more -->", ""))
  end
		
	def preview_image
    images.first if has_images?	  
	end

  def has_images?
    images && !images.empty?
  end
  

  def live?
    live && live == true
  end

  def to_param
		path
	end
	
	
	private
	
    def render(val)
      val = val.is_a?(Symbol) ? send(val) : val
      RDiscount.new(val).to_html.html_safe
    end
		
    def create_path
  		#downcase.gsub(/\s/, '-').gsub(/[^a-z0-9\-\_]/, '').gsub(/[\-]+/, '-')
  		count = 2
  		new_path = title.to_s.parameterize
  		exists = path_exists?(new_path)
  		while exists do
  			dupe_path = "#{new_path}_#{count}"
  			exists = path_exists?(dupe_path)
  			count += 1
  		end
  		self.path = dupe_path || new_path
  	end
  	
  	def path_exists?(new_path)
  		post = ::Post.find_by_path(new_path)
  		post != nil && !(post == self)
  	end
	
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
spree_essential_blog-0.1.0 app/models/post.rb
spree_essential_blog-0.1.0.rc1 app/models/post.rb