Class: Redtape::Form

Inherits:
Object
  • Object
show all
Extended by:
ActiveModel::Naming, Forwardable
Includes:
ActiveModel::Callbacks, ActiveModel::Conversion, ActiveModel::Validations
Defined in:
lib/redtape.rb

Instance Method Summary collapse

Constructor Details

#initialize(controller, args = {}) ⇒ Form

Returns a new instance of Form.



30
31
32
33
34
35
36
# File 'lib/redtape.rb', line 30

def initialize(controller, args = {})
  if controller.respond_to?(:populate_individual_record) && args[:whitelisted_attrs]
    fail DuelingBanjosError, "Redtape::Form does not accept both  #{controller.class}#populate_individual_record and the 'whitelisted_attrs' argument"
  end

  @factory = ModelFactory.new(factory_args_for(controller, args))
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args, &block) ⇒ Object



68
69
70
71
72
73
74
# File 'lib/redtape.rb', line 68

def method_missing(*args, &block)
  if @factory.model
    @factory.model.send(*args, &block)
  else
    super
  end
end

Instance Method Details

#persisted?Boolean

Forms are never themselves persisted

Returns:

  • (Boolean)


39
40
41
# File 'lib/redtape.rb', line 39

def persisted?
  false
end

#saveObject



54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/redtape.rb', line 54

def save
  if valid?
    begin
      ActiveRecord::Base.transaction do
        @factory.save!
      end
    rescue ActiveRecord::RecordInvalid
      # This shouldn't even happen with the #valid? above.
    end
  else
    false
  end
end

#valid?Boolean

Returns:

  • (Boolean)


43
44
45
46
47
48
49
50
51
52
# File 'lib/redtape.rb', line 43

def valid?
  model = @factory.populate_model
  valid = model.valid?

  # @errors comes from ActiveModel::Validations. This may not
  # be a legit hook.
  @errors = model.errors

  valid
end