Class: Hai::Create

Inherits:
Object
  • Object
show all
Defined in:
lib/hai/create.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, context) ⇒ Create

Returns a new instance of Create.



5
6
7
8
9
# File 'lib/hai/create.rb', line 5

def initialize(model, context)
  @model = model
  @context = context
  @context[:model] = model
end

Instance Attribute Details

#contextObject

Returns the value of attribute context.



3
4
5
# File 'lib/hai/create.rb', line 3

def context
  @context
end

#modelObject

Returns the value of attribute model.



3
4
5
# File 'lib/hai/create.rb', line 3

def model
  @model
end

Instance Method Details

#execute(**attrs) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/hai/create.rb', line 11

def execute(**attrs)
  id = attrs.delete(:id)
  instance = id ? model.find(id) : model.new

  return unauthorized_error unless check_policy(instance)

  instance.assign_attributes(**attrs) unless attrs.empty?

  run_action_modification(instance)

  if instance.save
    { errors: [], result: instance }
  else
    { errors: instance.errors.map(&:full_message), result: nil }
  end
end