./lib/lux/api/lib/model_api.rb in lux-fw-0.1.35 vs ./lib/lux/api/lib/model_api.rb in lux-fw-0.2.1
- old
+ new
@@ -34,11 +34,12 @@
def show
error "Object not found" unless @object
can? :read, @object
- @object.attributes
+
+ attributes
end
def create
@object = @class_name.constantize.new
@@ -59,51 +60,57 @@
message '%s created' % @class_name.capitalize
else
error 'object not created, error unknown'
end
- response.meta :path, @object.path if @object.respond_to?(:path)
+ add_response_object_path
- @object.attributes
+ attributes
end
def update
error "Object not found" unless @object
for k,v in @params
@object.send("#{k}=", v) if @object.respond_to?(k.to_sym)
end
can? :update, @object
+
+ @object.updated_at = Time.now.utc if @object.respond_to?(:updated_at)
@object.save if @object.valid?
+
report_errros_if_any @object
+
response.message '%s updated' % @class_name
- response.meta :path, @object.path if @object.respond_to?(:path)
- @object.attributes
+
+ add_response_object_path
+
+ attributes
end
# if you put active boolean field to objects, then they will be unactivated on destroy
- def destroy
+ def destroy force: false
error "Object not found" unless @object
can? :delete, @object
- if @object.respond_to?(:is_active)
+ if !force && @object.respond_to?(:is_active)
@object.update is_active: false
message 'Object deleted (exists in trashcan)'
- elsif @object.respond_to?(:active)
+ elsif !force && @object.respond_to?(:active)
@object.update active: false
message 'Object deleted (exists in trashcan)'
else
@object.destroy
message '%s deleted' % @object.class.name
end
report_errros_if_any @object
- @object.attributes
+ attributes
end
def undelete
error "Object not found" unless @object
can? :create, @object
@@ -117,31 +124,41 @@
end
response.message = 'Object raised from the dead.'
end
+ private
+
def report_errros_if_any obj
- if obj.errors.count > 0
- for k, v in obj.errors
- desc = v.join(', ')
+ return if obj.errors.count == 0
- response.error k, desc
- response.error desc
- # desc = "#{k} #{desc}" if desc.starts_with?('is ')
- end
+ for k, v in obj.errors
+ desc = v.join(', ')
- Lux.page.status 400
-
- return true
+ response.error k, desc
+ response.error desc
end
- false
+ error
end
- def can?(action, object)
- ModelPolicy.can?(action: action, model: object, user: Lux.page.var.user) do |err|
- msg = 'No %s permission for %s' % [action.to_s.sub('?',''), Lux.page.var.user ? Lux.page.var.user.email : :guests]
+ def can? action, object
+ object.can?(action) do |err|
+ msg = 'No %s permission for %s' % [action.to_s.sub('?',''), Lux.current.var.user ? Lux.current.var.user.email : :guests]
msg += ' on %s' % object.class.name if object
error msg
end
end
+
+ def add_response_object_path
+ begin
+ response.meta :path, @object.path if @object.respond_to?(:path)
+ rescue
+ nil
+ end
+ end
+
+ def attributes
+ @object.attributes.pluck(:id, :name, :email)
+ end
+
end