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) ⇒ Object

Returns true if equivalent.

Returns:

  • (Object)

    other



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:

  • (Object)

    raw model instance



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

def __raw_model = model

#contextSymbol

Returns :save or :destroy.

Returns:

  • (Symbol)

    :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:

  • (Boolean)


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

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.



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!InnerModel

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

Returns:



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

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

#valid?Boolean

Returns:

  • (Boolean)


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

def valid? = !invalid?