Module: SkinnyControllers::Operation::ModelHelpers
- Included in:
- Base
- Defined in:
- lib/skinny_controllers/operation/model_helpers.rb
Instance Method Summary collapse
- #model ⇒ Object
- #model_from_id ⇒ Object
- #model_from_named_id(key, id) ⇒ Object
- #model_from_params ⇒ Object
- #model_from_scope(scope = params[:scope]) ⇒ Object
- #sanitized_params ⇒ Object
- #scoped_model(scoped_params) ⇒ Object
Instance Method Details
#model ⇒ Object
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/skinny_controllers/operation/model_helpers.rb', line 4 def model # TODO: not sure if multiple ids is a good idea here # if we don't have a(ny) id(s), get all of them @model ||= if params[:scope] model_from_scope elsif (key = params.keys.grep(/\_id$/)).present? # hopefully there is only ever one of these passed id = params[key.first] model_from_named_id(key.first, id) elsif id_from_params model_from_id else model_from_params end end |
#model_from_id ⇒ Object
69 70 71 |
# File 'lib/skinny_controllers/operation/model_helpers.rb', line 69 def model_from_id model_class.find(id_from_params) end |
#model_from_named_id(key, id) ⇒ Object
51 52 53 54 55 56 57 58 |
# File 'lib/skinny_controllers/operation/model_helpers.rb', line 51 def model_from_named_id(key, id) name, _id = key.split('_') name = name.camelize model_from_scope( id: id, type: name ) end |
#model_from_params ⇒ Object
38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/skinny_controllers/operation/model_helpers.rb', line 38 def model_from_params ar_proxy = model_class.where(sanitized_params) if ar_proxy.respond_to? SkinnyControllers.accessible_to_scope # It's better to filter in sql, than in the app, so if there is # a way to do the filtering in active query, do that. This will help # mitigate n+1 query scenarios return ar_proxy.accessible_to(current_user) end ar_proxy end |
#model_from_scope(scope = params[:scope]) ⇒ Object
60 61 62 63 64 65 66 67 |
# File 'lib/skinny_controllers/operation/model_helpers.rb', line 60 def model_from_scope(scope = params[:scope]) if scoped = scoped_model(scope) association = association_name_from_object scoped.send(association) else fail "Parent object of type #{scope[:type]} not accessible" end end |
#sanitized_params ⇒ Object
21 22 23 24 |
# File 'lib/skinny_controllers/operation/model_helpers.rb', line 21 def sanitized_params keys = (model_class.column_names & params.keys) params.slice(*keys).symbolize_keys end |
#scoped_model(scoped_params) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/skinny_controllers/operation/model_helpers.rb', line 26 def scoped_model(scoped_params) unless @scoped_model klass_name = scoped_params[:type] operation_class = Lookup::Operation.operation_of(klass_name, DefaultVerbs::Read) operation = operation_class.new(current_user, id: scoped_params[:id]) @scoped_model = operation.run self. = !!@scoped_model end @scoped_model end |