Class: XML::Digester::SetPropertyRule

Inherits:
RulesBase
  • Object
show all
Defined in:
lib/xml/digestr.rb

Overview

Rule that sets a single ruby attribute on the top stack object. The attribute name and value to set are obtained from the specified XML attributes. The attribute is set in the begin event.

Instance Attribute Summary

Attributes inherited from RulesBase

#digester, #next, #pattern, #prev

Instance Method Summary collapse

Methods inherited from RulesBase

#body, #end, #finish

Constructor Details

#initialize(pattern, name_attr = 'name', value_attr = 'value', type = String, &blk) ⇒ SetPropertyRule

call-seq:

SetPropertyRule.new(pattern, name_attr = 'name', value_attr = 'value', type = String)
SetPropertyRule.new(pattern, name_attr = 'name', value_attr = 'value', type = String) { |target, attr, value| ... }

Create a new SetPropertyRule that will set the ruby attribute named by the ‘name_attr’ XML attribute to the value specified by the ‘value_attr’ XML attribute. Given, for example, a rule:

SetPropertyRule.new('*/a', 'foo_name', 'foo_val')

And the following element:

<a foo_name='foo', foo_value='bar'/>

The message sent to the top object on the stack would look like:

top.send(:foo=, 'bar')

You may optionally specify a coercion type, which should be the class the value should be converted to. The same rules apply as with the SetPropertiesRule.

If a block is supplied, it is called (during begin). The target argument supplies the top stack object, while attr and value supply the attribute name and value, processed according to the mapping rules. The block should set the attribute appropriately.



238
239
240
241
242
# File 'lib/xml/digestr.rb', line 238

def initialize(pattern, name_attr = 'name', value_attr = 'value', type = String, &blk)
  super(pattern)
  @name_attr, @value_attr, @blk = name_attr, value_attr, blk
  @type = type
end

Instance Method Details

#begin(namespace, name, attrs) ⇒ Object

:nodoc:



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/xml/digestr.rb', line 244

def begin(namespace, name, attrs) #:nodoc:
  dig = @digester
  if name = attrs[@name_attr]
    value = attrs[@value_attr]
    
    if ltype = @type   
      begin
        (value = send(ltype.name,value)) unless ltype == String
      rescue ArgumentError, TypeError
        if dig.pedantic?
          raise Error, $!.message
        end
      end
    end

    if (top = dig.peek)
      if b = @blk
        b.call(top, name, value)
      else
        begin
          top.send("#{name}=", value)
        rescue NoMethodError
          if dig.pedantic?
            raise Error,
                "Unknown property attribute: #{name} for #{top.inspect}"
          end
          nil
        end
      end
    end
  end
end