Module: C3sModel

Defined in:
lib/model.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

IGNORE_ATTR =

Attributes ignored and not included on model xml by default

["created_at", "updated_at", "id", "jid"]

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/model.rb', line 4

def self.included(base)
  if !base.ancestors.include?(ActiveRecord::Base)
    base.class_eval do
      cattr_accessor :attrs
      def attributes
        # <published> element assumed as being present no need to add this in your
        # models via "attribute" method.
        attr_hash = {}
        attrs.each do |a|
          attr_hash[a.to_s] = self.send(a.to_s) if self.respond_to?(a.to_s)
        end
        attr_hash
      end

      def attributes=(att, guard_protected_attributes)
        att.each do |key, val|
          self.attrs << key.to_s
          self.send("#{key.to_s}=", val) if self.respond_to?(key.to_s)
        end
      end
    end
  end
  base.extend(ClassMethods)
  # auto-add the published attribute
  base.attribute :published
end

Instance Method Details

#_class_nameObject

Returns the class name for this model without module name



54
55
56
# File 'lib/model.rb', line 54

def _class_name
  @class_name ||= self.class.name.split("::").last.downcase
end

#first_element(options = {}) ⇒ Object

Returns the first element for the model xml



87
88
89
90
91
92
93
# File 'lib/model.rb', line 87

def first_element(options={})
  return options[:parent] if options[:parent]

  name = self._class_name
  name = name.pluralize if options[:plural]
  REXML::Element.new(name)
end

#nodesObject

Gets the model nodes hash



60
61
62
63
64
65
66
67
68
# File 'lib/model.rb', line 60

def nodes
  nodes = self.attributes
  nodes.each do |key, val|
    if IGNORE_ATTR.include?(key) or key.match(/.+_id/)
      nodes.delete(key)
    end
  end
  nodes.keys
end

#to_xml(options = {}) ⇒ Object

Gets the model xml to include in a packet.

options
Hash

options



73
74
75
76
77
78
79
80
81
82
83
# File 'lib/model.rb', line 73

def to_xml(options={})
  xml = first_element(options)
  xml.add_attribute('xmlns', self.xmlns)
  self.attributes.each do |key, val|
    # Don't include ignored attributes or foreign keys
    if !IGNORE_ATTR.include?(key) && !key.match(/.+_id/)
      xml.add REXML::Element.new(key).add_text(val.to_s)
    end
  end
  xml
end

#update_attributes(attributes = {}) ⇒ Object

Updates multiple attributes at once

attributes
Hash

the attributes hash



48
49
50
# File 'lib/model.rb', line 48

def update_attributes(attributes={})
  self.send(:attributes=, attributes, false)
end

#xmlnsObject

Returns a default namespace based on class name



97
98
99
# File 'lib/model.rb', line 97

def xmlns
  "http://c3s.av.it.pt/#{self._class_name}"
end