-
-
Save mustmodify/2254515 to your computer and use it in GitHub Desktop.
| <?php | |
| class User | |
| { | |
| public $admin; | |
| public $roles = array(); | |
| function roles() | |
| { | |
| if (isset($this)) | |
| { | |
| return $roles; | |
| } | |
| else | |
| { | |
| return array('admin', 'manager', 'rep', 'customer', 'user'); | |
| } | |
| } | |
| function has_role( $needle ) | |
| { | |
| foreach ($this->roles as $role) | |
| { | |
| if($role == $needle) | |
| { | |
| return true; | |
| } | |
| } | |
| return false; | |
| } | |
| function can_view($entity) | |
| { | |
| if( $this->has_role('admin') ) | |
| { | |
| return true; | |
| } | |
| else | |
| { | |
| if( $entity == "thing" && $this->has_role('manager') ) | |
| { | |
| return true; | |
| } | |
| else | |
| { | |
| return false; | |
| } | |
| } | |
| } | |
| function can_edit($entity) | |
| { | |
| } | |
| function can_delete($entity) | |
| { | |
| return false; | |
| } | |
| function can_manage($entity) | |
| { | |
| } | |
| } | |
| $a = new User(); | |
| if( $a->can_view('whatever') ) | |
| { | |
| echo "yep\n"; | |
| } | |
| else | |
| { | |
| echo "as expected, non-admins can't view random stuff\n"; | |
| } | |
| array_push($a->roles, 'admin'); | |
| if( $a->can_view('whatever') ) | |
| { | |
| echo "as expected, admins can view anything."; | |
| } | |
| else | |
| { | |
| echo "uh oh"; | |
| } | |
| ?> |
Thanks for your contribution, always appreciated.
I don't mind Ruby overall but I feel more fortunate to be writing a language, PHP, that feels more like a language, than Ruby which to me looks ugly-ish. Though its a matter of taste quite clearly, that and the fact that I've not worked on that many commercial Ruby projects to have a soft spot for it - yet.
You did a pretty good job at making your gist look ugly as heck.
Instead some simple improvements make a difference...
$a = new User();
if ( $a->can_view('whatever') ) {
echo "yep\n";
} else {
echo "as expected, non-admins can't view random stuff\n";
}Much nicer, easier to understand. (_extra line breaks optional_)
For a nice clean implementation that's easy to understand, checkout...
https://github.com/danieleds/SimpleRoles
...whom was also inspired by CanCan.
Keep up the good work!
ps. I gave you a gold star too ;)
@mustmodify thanks for this, and I should say, writing more Ruby is making me like PHP more -- just saying.
I would like to thank PHP for reminding me of how fortunate I am to be writing Ruby.