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:

  • model (Object)

    the model instance.

  • context (Symbol) (defaults to: :save)

    :save or :destroy

  • context (Proc) (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:

  • other (Object)

Returns:

  • (Boolean)


77
78
79
80
81
82
83
# File 'lib/active_record_compose/inner_model.rb', line 77

def ==(other)
  return false unless self.class == other.class
  return false unless __raw_model == other.__raw_model # steep:ignore
  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:

  • (Object)

    raw model instance



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

def __raw_model = model

#contextSymbol

Returns :save or :destroy.

Returns:

  • (Symbol)

    :save or :destroy



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/active_record_compose/inner_model.rb', line 18

def context #: ActiveRecordCompose::context
  c = @context
  ret =
    if c.is_a?(Proc)
      if c.arity == 0
        # @type var c: ^() -> context
        c.call
      else
        # @type var c: ^(_ARLike) -> context
        c.call(model)
      end
    else
      c
    end
  ret.presence_in(i[save destroy]) || :save
end

#invalid?Boolean

Returns:

  • (Boolean)


61
62
63
64
65
66
67
68
# File 'lib/active_record_compose/inner_model.rb', line 61

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:

  • (Boolean)

    returns true on success, false on failure.



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

#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.



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

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

#valid?Boolean

Returns:

  • (Boolean)


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

def valid? = !invalid?