Skip to content

Instantly share code, notes, and snippets.

@steveklabnik
Created December 12, 2011 13:04
Show Gist options
  • Select an option

  • Save steveklabnik/1467062 to your computer and use it in GitHub Desktop.

Select an option

Save steveklabnik/1467062 to your computer and use it in GitHub Desktop.
Wtf cancan?
# Article is a normal AR class, no methods, just attributes. free is a boolean attribute.
#
# /articles/1 is free, /articles/2 is not.
#
# I want only logged in users to read non-free articles. But the :free => true line seems to be enabling
# reading all of them; when I comment it out, non-logged-in users can't read anything. But with it
# uncommented, they can read everything. WTF?
#
# User.new.is? :user is false, and so is User.new.is? :admin.
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.is? :user
can :show, Article
elsif user.is? :admin
can [:show, :create, :update], Article
else
can :show, Article, :free => true
cannot :show, Article, :free => false
end
end
end
class ArticleRepository
class << self
delegate :find, :new, :to => Article
def root
Article.first
end
end
end
class ArticlesController < ApplicationController
def new
@article = ArticleRepository.new
end
def create
@article = ArticleRepository.new params[:article]
@article.update_attributes(params[:article])
@article.save
redirect_to article_path(@article)
end
def show
#begin
@article = ArticleRepository.find(params[:id])
authorize!(:show, @article)
#rescue ActiveRecord::RecordNotFound
# render :create
# return
#end
end
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
include RoleModel
roles :admin, :user
end
@guilherme
Copy link

@steveklabnik, i've been thinking about why use the repository pattern instead of access directly into ActiveRecord? http://martinfowler.com/eaaCatalog/repository.html it says that repository is about to mediate the domain and data mapping layer(active record in this case). but in practice what are the benefits of using this? thank you.

@steveklabnik
Copy link
Author

@guilherme ... pay attention to my blog sometime next week.

@guilherme
Copy link

@steveklanik i'm curious about it .. i can't wait until next week. :( :~

@steveklabnik
Copy link
Author

Here's the one sentence answer: It decreases the coupling in your code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment