Module: Cms::Behaviors::DynamicAttributes::InstanceMethods

Defined in:
lib/cms/behaviors/dynamic_attributes.rb

Instance Method Summary collapse

Instance Method Details

#assign_attributes(new_attributes, options = {}) ⇒ Object

Overrides the assign_attributes= defined in ActiveRecord::Base(active_record/base.rb)

The only difference is that this doesn't check to see if the model responds_to the method before sending it

Not happy with this copy/paste duplication, but its merely an update to the previous Rails 2/3 behavior Must remain PUBLIC so other rails methods can call it (like ActiveRecord::Persistence#update_attributes)



232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/cms/behaviors/dynamic_attributes.rb', line 232

def assign_attributes(new_attributes, options = {})
  return unless new_attributes

  attributes = new_attributes.stringify_keys
  role = options[:as] || :default

  multi_parameter_attributes = []

  # Disabling mass assignment protection for attributes, might be a terrible idea, but dynamic_attributes are really wonky.
  #unless options[:without_protection]
  #  attributes = sanitize_for_mass_assignment(attributes, role)
  #end

  attributes.each do |k, v|
    if k.include?("(")
      multi_parameter_attributes << [k, v]
    else
      # Dynamic Attributes will take ALL setters (unlike ActiveRecord)
      send("#{k}=", v)
    end
  end

  assign_multiparameter_attributes(multi_parameter_attributes)
end

#dynamic_attributes(model) ⇒ Object

Return a list of valid dynamic attributes for the given model. Return nil if any field is allowed. If you want to say no field is allowed then return an empty array. If you just have a static list the :fields option is most likely easier.



220
221
222
# File 'lib/cms/behaviors/dynamic_attributes.rb', line 220

def dynamic_attributes(model)
  ; nil
end

#is_dynamic_attribute?(attr, model) ⇒ Boolean

Will determine if the given attribute is a dynamic attribute on the given model. Override this in your class to provide custom logic if the #dynamic_attributes method or the :fields option are not flexible enough. If you override this method :fields and #dynamic_attributes will not apply at all unless you implement them yourself.

Returns:

  • (Boolean)


209
210
211
212
213
214
# File 'lib/cms/behaviors/dynamic_attributes.rb', line 209

def is_dynamic_attribute?(attr, model)
  attr = attr.to_s
  return dynamic_options[model.name][:fields].include?(attr) unless dynamic_options[model.name][:fields].nil?
  return dynamic_attributes(model).collect { |f| f.to_s }.include?(attr) unless dynamic_attributes(model).nil?
  true
end