Module: GrumpyMapper::ClassMethods

Defined in:
lib/grumpymapper.rb

Instance Method Summary collapse

Instance Method Details

#has_many(name, xpath, klass) ⇒ Object



39
40
41
42
# File 'lib/grumpymapper.rb', line 39

def has_many(name, xpath, klass)
  attr_accessor name
  @attributes[name] = Property::new(xpath, klass, true, [])
end

#has_one(name, xpath, klass, default = nil) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/grumpymapper.rb', line 23

def has_one(name, xpath, klass, default=nil)
  attr_accessor name
  if default.nil?
    default = if klass.eql?(String)
      ""
    elsif klass.eql?(Integer)
      0
    elsif klass.eql?(Float)
      0.0
    else
      nil
    end
  end
  @attributes[name] = Property::new(xpath, klass, false, default)
end

#parse(xml) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/grumpymapper.rb', line 44

def parse(xml)
  result = []
  Nokogiri::XML(xml).xpath(@tag).each do |tag|
    entity = new
    @attributes.each do |key,property|
      matches = tag.xpath(property.xpath)
      if matches.size > 0
        matches = if property.klass.eql?(Integer)
          matches.map(&:text).map(&:to_i)
        elsif property.klass.eql?(Float)
          matches.map(&:text).map(&:to_f)
        elsif property.klass.eql?(Boolean)
          matches.map(&:text).map do |m|
            %w(true t 1).include?(m) ? true : false
          end
        elsif property.klass.eql?(Date)
          matches.map(&:text).map do |m|
            Date::parse(m)
          end
        elsif property.klass.eql?(DateTime)
          matches.map(&:text).map do |m|
            DateTime::parse(m)
          end          
        elsif property.klass.eql?(String)
          matches.map(&:text)
        else
          matches.map do |m|
            property.klass.parse(m.to_s).first
          end
        end
        if property.multi
          entity.send(:"#{key}=", matches)
        else
          entity.send(:"#{key}=", matches.first)
        end
      else
        entity.send(:"#{key}=", property.default)
      end # if matches.size > 0
    end # @attributes.each
    result << entity
  end # each tag
  return result
end

#tag(xpath) ⇒ Object



19
20
21
# File 'lib/grumpymapper.rb', line 19

def tag(xpath)
  @tag = xpath
end