Skip to content

Instantly share code, notes, and snippets.

@hamstar
Created November 10, 2012 18:22
Show Gist options
  • Select an option

  • Save hamstar/4052016 to your computer and use it in GitHub Desktop.

Select an option

Save hamstar/4052016 to your computer and use it in GitHub Desktop.
u = User.first
p = Page.first
# Only like this does it work
p.user = u
u.pages << p
# this does not work (does not set the user_id in the pages table)
> p.user(u).save
(0.1ms) begin transaction
SQL (6.1ms) INSERT INTO "pages" ("created_at", "name", "updated_at", "user_id") VALUES (?, ?, ?, ?) [["created_at", Sat, 10 Nov 2012 17:08:39 UTC +00:00], ["name", "testpages"], ["updated_at", Sat, 10 Nov 2012 17:08:39 UTC +00:00], ["user_id", nil]]
(16.3ms) commit transaction
=> true
# nor does this
> u.pages << p
(0.1ms) begin transaction
(0.1ms) commit transaction
=> false
class Page < ActiveRecord::Base
validates_presence_of :user
attr_accessible :name, :body, :change_comment, :user, :user_id
attr_accessor :body, :change_comment, :user
FORMAT = :markdown
belongs_to :user
before_create :create_page
before_update :update_page
before_destroy :delete_page
def content
page.formatted_data
end
def raw_content
page.raw_data
end
def author
page.version.author.name.gsub(/<>/, '')
end
def date
page.version.authored_date
end
def preview(data)
wiki.preview_page('Preview', data, FORMAT).formatted_data
end
private
def wiki
@@gollum ||= Gollum::Wiki.new user.wiki_path
end
def page
wiki.page(self.name)
end
def commit
{:message => change_comment || "", :name => user.fullname, :author => "#{user.fullname} <#{user.email}>"}
end
def create_page
wiki.write_page(name, FORMAT, body || '', commit)
end
def update_page
wiki.update_page(page, name, FORMAT, body || self.raw_content, commit)
end
def delete_page
#wiki.delete_page(page, COMMIT)
end
end
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
after_create :create_user_wiki
#before_destory :delete_user_wiki
after_create :create_start_page
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :fullname, :wiki_path
# attr_accessible :title, :body
has_many :pages
def has_wiki?
File.directory? wiki_path
end
def wiki_path
wiki_path = Rails.root.join("wikis", "#{username}.git").to_s
end
private
def create_user_wiki
if !File.directory? wiki_path
Dir.mkdir wiki_path
Grit::Repo.init_bare wiki_path
end
end
def create_start_page
page = Page.new name: "start", body: "o hai thar", change_comment: "created page", user: self
page.save
pages << page
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment