Class: HasMetadata::Model

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
lib/has_metadata/model.rb

Overview

Base class of the Metadata model. Functionality is moved to this class to make changes to the model easier. See the ‘Metadata` method for more information.

Instance Method Summary collapse

Instance Method Details

#changed_metadataHash<String, Object>

Returns A hash of metadata fields that have been altered.

Returns:

  • (Hash<String, Object>)

    A hash of metadata fields that have been altered.



70
71
72
# File 'lib/has_metadata/model.rb', line 70

def 
  changed_attributes.except(*attribute_names)
end

#set_fields(fields) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/has_metadata/model.rb', line 17

def set_fields(fields)
  return self if @_fields_set
  @_fields_set = true
  
  singleton_class.send(:define_method, :attribute_method?) do |name|
    name = name.to_sym
    super(name) or fields.include?(name)
  end

  # override attribute prefix/suffix methods to get full first-class
  # property functionality

  singleton_class.send(:define_method, :attribute) do |name|
    name = name.to_sym
    super(name) unless fields.include?(name)

    options = fields[name] || {}
    default = options.include?(:default) ? options[:default] : nil
    data.include?(name) ? data[name] : default
  end
  singleton_class.send :alias_method, :attribute_before_type_cast, :attribute

  singleton_class.send(:define_method, :query_attribute) do |name|
    name = name.to_sym
    super(name) unless fields.include?(name)

    options = fields[name] || {}
    if options.include?(:type) then
      if options[:type].ancestors.include?(Numeric) then
        not send(name).zero?
      else
        not send(name).blank?
      end
    else
      not send(name).blank?
    end
  end

  singleton_class.send(:define_method, :attribute=) do |name, value|
    name = name.to_sym
    super(name, value) unless fields.include?(name)

    options = fields[name] || {}
    data_will_change!
    attribute_will_change! name.to_s
    data[name] = HasMetadata.(value, options[:type])
  end

  self
end