Class: ActiveRecordCompose::InnerModel

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record_compose/inner_model.rb

Instance Method Summary collapse

Constructor Details

#initialize(model, context: :save) ⇒ InnerModel

Returns a new instance of InnerModel.

Parameters:

  • the model instance.

  • (defaults to: :save)

    :save or :destroy

  • (defaults to: :save)

    proc returning either :save or :destroy



10
11
12
13
# File 'lib/active_record_compose/inner_model.rb', line 10

def initialize(model, context: :save)
  @model = model
  @context = context
end

Instance Method Details

#==(other) ⇒ Boolean

Returns true if equivalent.

Parameters:

Returns:



65
66
67
68
69
70
71
# File 'lib/active_record_compose/inner_model.rb', line 65

def ==(other)
  return false unless self.class == other.class
  return false unless __raw_model == other.__raw_model
  return false unless context == other.context

  true
end

#__raw_modelObject

Returns a model instance of raw, but it should be noted that application developers are not expected to use this interface.

Returns:

  • raw model instance



77
# File 'lib/active_record_compose/inner_model.rb', line 77

def __raw_model = model

#contextSymbol

Returns :save or :destroy.

Returns:

  • :save or :destroy



18
19
20
21
# File 'lib/active_record_compose/inner_model.rb', line 18

def context
  ret = @context.respond_to?(:call) ? @context.call(model) : @context
  ret.presence_in(%i[save destroy]) || :save
end

#invalid?Boolean

Returns:



49
50
51
52
53
54
55
56
# File 'lib/active_record_compose/inner_model.rb', line 49

def invalid?
  case context
  when :destroy
    false
  else
    model.invalid?
  end
end

#saveBoolean

Execute save or destroy. Returns true on success, false on failure. Whether save or destroy is executed depends on the value of context.

Returns:

  • returns true on success, false on failure.



27
28
29
30
31
32
33
34
# File 'lib/active_record_compose/inner_model.rb', line 27

def save
  case context
  when :destroy
    model.destroy
  else
    model.save
  end
end

#save!Object

Execute save or destroy. Unlike #save, an exception is raises on failure. Whether save or destroy is executed depends on the value of context.



39
40
41
42
43
44
45
46
# File 'lib/active_record_compose/inner_model.rb', line 39

def save!
  case context
  when :destroy
    model.destroy!
  else
    model.save!
  end
end

#valid?Boolean

Returns:



59
# File 'lib/active_record_compose/inner_model.rb', line 59

def valid? = !invalid?