Module: HasAttributes::ClassMethods

Defined in:
lib/has_attributes.rb

Instance Method Summary collapse

Instance Method Details

#has_attributes(*attrs) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/has_attributes.rb', line 11

def has_attributes(*attrs)
  options = attrs.last.instance_of?(Hash) ? attrs.pop : {}
  inherit_parent_attributes = options[:inherit] != false

  parent_attributes = if superclass.respond_to?(:model_attributes) && superclass.model_attributes.is_a?(Set)
    superclass.model_attributes.dup
  else
    Set.new
  end

  attrs = (model_attributes || Set.new).merge(attrs.map(&:to_sym))

  if inherit_parent_attributes
    attrs = parent_attributes.merge(attrs)
  elsif !parent_attributes.empty?
    methods_to_remove = parent_attributes.reduce([]) do |memo, getter|
      setter = (getter.to_s << "=").to_sym
      memo.push(getter) if public_method_defined?(getter)
      memo.push(setter) if public_method_defined?(setter)
      memo
    end
    instance_eval {undef_method *methods_to_remove}
  end

  self.model_attributes = attrs
  instance_eval {attr_accessor *attrs}
end