Created
June 16, 2013 19:15
-
-
Save kreeger/5793055 to your computer and use it in GitHub Desktop.
Rails model with Tumblr download capabilities.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Post < ActiveRecord::Base | |
| include Renderable | |
| belongs_to :posted_by, class_name: 'User' | |
| scope :recent, -> { order('published_at desc') } | |
| validates :title, :body, :slug, :posted_by_id, presence: true | |
| validates :title, :slug, uniqueness: { case_sensitive: false } | |
| before_validation :slugify | |
| paginates_per 5 | |
| acts_as_taggable | |
| def self.published(published) | |
| condition = published ? 'published_at <= ?' : 'published_at > ?' | |
| where(condition, Time.now.utc) | |
| end | |
| def self.import_all_from_tumblr(user) | |
| client = Tumblr::Client.new | |
| post_data = client.posts("kreeger.tumblr.com", type: 'text', limit: 40) | |
| post_data['posts'].each { |post| self.create_from_tumblr(post, user) } | |
| post_data = client.posts("kreeger.tumblr.com", type: 'link', limit: 40) | |
| post_data['posts'].each { |post| self.create_from_tumblr(post, user) } | |
| end | |
| def self.create_from_tumblr(tumblr_post, user) | |
| type = tumblr_post['type'] | |
| return nil unless %w(text link).include?(type) | |
| date = Time.at(tumblr_post['timestamp']) | |
| tags = tumblr_post['tags'].join(', ') | |
| title = tumblr_post['title'] | |
| return nil unless title | |
| if type == 'text' | |
| body = tumblr_post['body'] | |
| read_more_uri = nil | |
| elsif type == 'link' | |
| body = tumblr_post['description'] | |
| read_more_uri = tumblr_post['url'] | |
| end | |
| content_type = 'html' | |
| post = user.posts.create(title: title, body: body, published_at: date, | |
| read_more_uri: read_more_uri, content_type: content_type) | |
| user.tag(post, with: tags, on: :tags) | |
| end | |
| def rendered_summary | |
| self.send(content_type.to_sym, :summary) | |
| end | |
| def rendered_body | |
| self.send(content_type.to_sym, :body) | |
| end | |
| def slugify | |
| self.slug = self.title.to_slug | |
| end | |
| def to_param | |
| self.slug | |
| end | |
| end | |
| # == Schema Information | |
| # | |
| # Table name: posts | |
| # | |
| # id :integer not null, primary key | |
| # title :string(255) default(""), not null | |
| # summary :text | |
| # body :text default(""), not null | |
| # slug :string(255) default(""), not null | |
| # published_at :datetime not null | |
| # read_more_uri :string(255) | |
| # posted_by_id :integer | |
| # created_at :datetime | |
| # updated_at :datetime | |
| # content_type :string(255) default("markdown"), not null | |
| # | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment