вторник, 14 февраля 2017 г.

Ruby role-based authorization

When I just started to code ruby my experienced mates taught me a pretty good lesson. If you are about to code some feature, you should search for a gem first. The most common programming cases are already coded and formed into ruby gems. This advice works great for many other aspects of my life, not only programming.
Recently, I started a new prototype project with some common functionality like authentication and role-based authorization. This is where things like gem googling becomes terrible part. I'll describe requirements for my role model and my gem disappointments below.

Proper user-role-grants model
When you say "role model", you mean rolify gem, isn't you? I hope not, and that's why. Proper role model contains user model (pretty obvious), a role model and a grant. Grant is an opportunity to make a particular action with some class of objects (or even with certain object instance). Role is an aggregation of grants, usually named some way. It sounds paradoxically, but rolify gem has no proper role model, it has only grant model which is called by gem makers "role" for some reason. You can assign many different grants to your user instance, but you can not combine grants in one object other than user. When you need to assign the same role to another user instance you have to repeat all grants assignment as well. It's annoying, isn't it? Probably you can extend rolify with proper role layer, but it will looks weird. Like, user -> role_set -> role (which one is really a grant).

Roles persisted in the database
I thought it's popular case when you want all your roles (named combinations of grants) be persisted inside the database. It becomes useful when your user administrator needs to create a new role with unique set of grants without writing any code. Honestly, I found a policy design in gems like pundit and cancancan (cancan) storing grants inside ruby classes a weird decision. And that's where the_role gem comes in handy. It's almost Swiss knife for roles, but it has some limitations, and first of them "User has one role".

One user may have several roles at the same time (one-to-many relationship)
I think this statement is a subject of discuss, but I'll try to explain my vision. Usually, when you want to create user with several roles (more than one) it smells like a bad design decision. Typical approach is to create new role with all grants that you need. But there is another side assuming that you have one technical role for one business role. There are some situations when one person (and one user) combines several business roles, especially when business is small. In this cases one-to-many relationship seems pretty natural and verbose.

If you want a thing well done, do it yourself.

Discuss?

понедельник, 30 июня 2014 г.

GOA India

Сразу отмечу, что это мой первый выезд на пляжный отдых. До этого был только в Чехии и один день в Германии. Отель Chalston Beach Resort находится на побережье Аравийского моря Индийского океана, примерно по середине между двумя крупными пляжами ГОА: Калангут и Бага. Пляжи фактически плавно перетекают один в другой. Весь отель утопает в зелени цветов и пальм. За всем многообразием флоры следят сотрудники отеля, поливают, подстригают газон и кустики. Очень удачно продумано расположение зданий на территории отеля. Номера расположены в дальней от пляжа части, в тени пальм и отделены от него отельным ресторанчиком под навесом, продуваемым морским бризом. Были во многих заведениях на территории обоих пляжей. Отельный ресторанчик, однозначно, один из лучших в соотношении цена/качество. Вкусная и вполне разнообразная кухня и очень приветливые официанты, есть русское меню. Официанты и местные жители по-русски почти ничего не понимают, но отлично общаются на английском. Я даже успел подружится с одним из них. Рядом с рестораном отельные лежаки с зонтиками и выход на общий пляж. Можно пить коктейли не вставая с лежака. В Индии все пляжи муниципальные, в силу чего много людей гуляет вдоль моря как туристов так и местных. Не удивляйтесь когда будут местные просить сфотографироваться с Вами. Белая кожа - признак достатка, благополучия и успеха. Вход на территорию отеля с пляжа охраняется от назойливых торговцев да и представители власти в лице пляжной службы спасения. Спасатели вежливо отгоняют местных с куска пляжа прилегающего к отелю. Впрочем, Индийцы по-моему не особо расстраиваются по этому поводу, места на побережье всем хватает.

Собственно, ссылки на отель:
tophotels.ru
мой отзыв на tophotels.ru
booking.com
tripadvisor.ru

четверг, 23 сентября 2010 г.

Technolover vol.9

Буквально на днях знакомый знакомого выдал очередной сет отличной электронной музыки, уже 9-ый по счету. Не скажу что я большой любитель стиля Progressive House или направления Techno, однако, его творчество производит неизгладимо положительное впечатление. Встречайте - Armando Biz. Любителям прокатиться на машине под музыку - must have!