Created
November 4, 2012 17:55
-
-
Save ShadowBelmolve/4012778 to your computer and use it in GitHub Desktop.
A prototype of my next gem.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#app/filters/user.rb | |
FilterIt.create('user') do | |
requires :name, :class => String # stop the filter if no name is found on 'data' | |
if current_user.admin? # search in each context for one that respond to the method 'current_user' without an error | |
# optional will not raise an error if isn't found, if any validation fail it will be simply ignored. | |
optional :authorizantion_level, :class => Integer,:in => 0..10 | |
end | |
if current_user.manager? | |
optional :org_ids, :class => Array do | |
unless (is_creating_user rescue false) | |
data.each do |id| | |
# RefuseEntry will make :org_ids invalid, because it is optional the 'user' filter will not fail | |
# but the output will not have the :org_ids key | |
raise FilterIt::RefusedEntry unless current_user.orgs.include?(id) | |
end | |
end | |
end | |
end | |
end | |
#app/filters/org.rb | |
FilterIt.create('org') do | |
requires :name, :class => String | |
optional :users, :class => Hash do | |
# if final data is set the filter will use it, so :users will turn into the output of a map of 'user' filter | |
final_data = data.map do |user| | |
inherit :user, :data => user, :contexts => all_contexts + [{ :is_creating_user => true }] | |
end | |
end | |
end | |
#app/controllers/orgs_controller.rb | |
def create | |
# :contexts expect an array of objects, if the object is a hash, each key will | |
# be transformed in a method, otherwise it will be used by method_missing | |
# and if a context respond to the method without error it will be turned into a | |
# method for performance | |
data = FilterIt.filter(:org, :data => params[:org], :contexts => [self]) | |
if data | |
Org.create!(data) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment