Class: Rexle

Inherits:
Object
  • Object
show all
Defined in:
lib/rexle.rb

Defined Under Namespace

Classes: Element

Instance Method Summary collapse

Constructor Details

#initialize(x = nil) ⇒ Rexle

Returns a new instance of Rexle.



13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/rexle.rb', line 13

def initialize(x=nil)
      
  if x then
    procs = {
     String: proc {|x| parse_string(x)},
     Array: proc {|x| x},
     :"REXML::Document" =>  proc {|x| scan_doc x.root}
    }
    a = procs[x.class.to_s.to_sym].call(x)
    @doc = scan_element(*a)      
  end
  
end

Instance Method Details

#add_element(element) ⇒ Object Also known as: add



310
# File 'lib/rexle.rb', line 310

def add_element(element) @doc.root.add_element(element) end

#delete(xpath) ⇒ Object



314
# File 'lib/rexle.rb', line 314

def delete(xpath) @doc.element(xpath).delete end

#element(xpath) ⇒ Object



315
# File 'lib/rexle.rb', line 315

def element(xpath) @doc.element(xpath) end

#parse(x = nil) ⇒ Object

– end of element –



291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'lib/rexle.rb', line 291

def parse(x=nil)
  
  a = []
  
  if x then
    procs = {
     String: proc {|x| parse_string(x)},
     Array: proc {|x| x},
     :"REXML::Document" =>  proc {|x| scan_doc x.root}
    }
    a = procs[x.class.to_s.to_sym].call(x)
  else    
    a = yield
  end

  @doc = scan_element(*a)
  self
end

#rootObject



318
# File 'lib/rexle.rb', line 318

def root() @doc end

#text(xpath) ⇒ Object



316
# File 'lib/rexle.rb', line 316

def text(xpath) @doc.text(xpath) end

#to_sObject



317
# File 'lib/rexle.rb', line 317

def to_s() self.xml end

#writeObject



319
# File 'lib/rexle.rb', line 319

def write() "<?xml version='1.0' encoding='UTF-8'?>\n"  + xml end

#xmlObject



320
321
322
323
324
# File 'lib/rexle.rb', line 320

def xml()
  body = scan_print(self.root.children).join
  a = self.root.attributes.to_a.map{|k,v| "%s='%s'" % [k,v]}  
  "<%s%s>%s</%s>" % [self.root.name, a.empty? ? '' : ' ' + a.join(' '), body, self.root.name]
end

#xpath(path, &blk) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/rexle.rb', line 27

def xpath(path, &blk)

  # is it a function
  fn_match = path.match(/^(\w+)\(([^\)]+)\)$/)

  #    Array: proc {|x| x.flatten.compact}, 
  if fn_match.nil? then      
    procs = {
      Array: proc {|x| block_given? ? x : x.flatten }, 
      String: proc {|x| x},
      :"Rexle::Element" => proc {|x| [x]}
    }
    bucket = []
    result = @doc.xpath(path, bucket, &blk)

    procs[result.class.to_s.to_sym].call(result)
    
  else
    m, xpath_value = fn_match.captures
    method(m.to_sym).call(xpath_value)
  end

end