権限を調べる部分の実装

まず,Memberのオブジェクトからはhas_rightというメソッドで権限を持っているかどうかを調べます。
  # context is either a Blog, or an Item
  def has_right rightname, context
    #search role first.
    context.has_right rightname, self
  end

rightnameが権限の名前,例えば"browse"などになります。contextはコメントにもあるように,どのコンテキストで権限を判断するかと言うこと。ブログあるいはアイテムがcontextです。で,これは実際にはコンテキストに問い合わせて調べます。つまり,BlogクラスとItemクラスにはどちらもhas_rightというメソッドがあってそれが呼び出されます。これが昨日書いたダック・タイピング,すなわち同じメソッドを持っていたら同じものとして使える,ということになります。

Blogクラスのこの部分の実装はこう。
  def role_of member
    if !member
      return self.guest_role
    else
      t = Team.find(:first, :conditions=>["tblog=? and tmember=?", self.id, member.id])
      if t then
        return t.role
      else
        return self.user_role
      end
    end
  end
  
  def has_right rightname, member
    role = self.role_of member
    return role.attributes[rightname]
  end

下のhas_rightがメインで,ロールに対してフィールド名で取得するようにしています。実はこれだと関係ないフィールドまで取れてしまいますが,そこはガチガチにしなくてもいいだろうと判断しています。上のrole_ofでは,ログインしていない場合(memberがnil),ログインしているけどチームに入っていない場合,チームに入っている場合に分けてRoleを返します。前二つの場合はBlogのテーブル内のフィールド情報から取り出します。guest_roleやuser_roleはクラスの上の方でbelongs_toとして定義しています。

一方Itemクラスは
 def role_of member
   role = self.blog.role_of member
   itemrole = ItemRole.find(:first, :conditions=>["item_id=? and role_id=?",self.id, role.id])
   if itemrole then
     return itemrole
   else
     return role
   end
 end
 
  def has_right rightname, member
    role = self.role_of member
    return role.attributes[rightname]
  end 

has_rightの部分は実は同じですが,ここでもダック・タイピングもどきのことをしています。アイテムで独自の権限を決める場合はその情報はItemRoleというクラスに入っていますが,その場合もRoleクラスと同じようにattributes[rightname]で結果を取り出しています。role_ofの方は先ほどのBlogのrole_ofでRoleを取り出し,ItemRoleが存在すればそっち,しなければ取ってきたRoleを返します。


21 Jun, 2008 | Foodyn ( 実装メモ , 管理画面 ) | | Andy
« Prev item - Next Item »
---------------------------------------------

Comments


No comments yet. You can be the first!


Leave comment

© 2007 yoursite.com | Designed by DesignsByDarren
Ported to Nucleus CMS: Suvoroff