Module: MiniForm::Model::ClassMethods

Defined in:
lib/mini_form/model.rb

Instance Method Summary collapse

Instance Method Details

#attribute_namesObject



136
137
138
# File 'lib/mini_form/model.rb', line 136

def attribute_names
  @attribute_names ||= []
end

#attributes(*attributes, delegate: nil, prefix: nil, allow_nil: nil) ⇒ Object



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/mini_form/model.rb', line 145

def attributes(*attributes, delegate: nil, prefix: nil, allow_nil: nil)
  if prefix
    attribute_names.push(*attributes.map do |name|
      :"#{prefix == true ? delegate : prefix}_#{name}"
    end)
  else
    attribute_names.push(*attributes)
  end

  if delegate.nil?
    attr_accessor(*attributes)
  else
    delegate(*attributes, to: delegate, prefix: prefix, allow_nil: allow_nil)
    delegate(*attributes.map { |attr| "#{attr}=" }, to: delegate, prefix: prefix, allow_nil: allow_nil)
  end
end

#inherited(base) ⇒ Object



126
127
128
129
130
131
132
133
134
# File 'lib/mini_form/model.rb', line 126

def inherited(base)
  new_attribute_names = attribute_names.dup
  new_models_to_save  = models_to_save.dup

  base.instance_eval do
    @attribute_names = new_attribute_names
    @models_to_save  = new_models_to_save
  end
end

#main_model(model_name, **args) ⇒ Object



174
175
176
177
178
# File 'lib/mini_form/model.rb', line 174

def main_model(model_name, **args)
  delegate :id, :persisted?, :to_param, :new_record?, to: model_name

  model model_name, **args
end

#model(name, attributes: [], read: [], prefix: nil, allow_nil: nil, save: false) ⇒ Object

rubocop:disable Metrics/ParameterLists



162
163
164
165
166
167
168
169
170
171
172
# File 'lib/mini_form/model.rb', line 162

def model(name, attributes: [], read: [], prefix: nil, allow_nil: nil, save: false) # rubocop:disable Metrics/ParameterLists
  attr_accessor name

  attributes(*attributes, delegate: name, prefix: prefix, allow_nil: allow_nil) unless attributes.empty?

  delegate(*read, to: name, prefix: prefix, allow_nil: nil)

  validates name, 'mini_form/nested' => true

  models_to_save << name if save
end

#models_to_saveObject

:api: private



141
142
143
# File 'lib/mini_form/model.rb', line 141

def models_to_save
  @models_to_save ||= []
end