Class: Pump::Encoder

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

Direct Known Subclasses

Json, Xml

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root_name, encoder_config = nil, encoder_options = {}) { ... } ⇒ self

Creates a new XML-encoder with a root tag named after +root_name+.

Examples:

Create a simple encoder for a person with a name attribute:

Pump::Xml.new :person do
  tag :name
end

Create the same without usage of the DSL:

Pump::Xml.new :person, [{:name => :name}]

Create the same but without the xml instruct

Pump::Xml.new :person, :instruct => false do
  tag :name
end

The same again without DSL:


Pump::Xml.new :person, [{:name => :name}], :instruct => false

Yields:

  • an optional block to create the encoder with the Pump::Dsl



32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/pump/encoder.rb', line 32

def initialize(root_name, encoder_config=nil, encoder_options={}, &blk)
  if encoder_config.is_a?(Array)
    @encoder_config  = encoder_config
    @encoder_options = encoder_options || {}
  else
    raise ArgumentError unless block_given?
    @encoder_options = encoder_config || {}
    @encoder_config = Pump::Dsl.new(&blk).config
  end
  @root_name = root_name
  merge_base

  compile
end

Instance Attribute Details

#baseObject (readonly)

Returns the value of attribute base.



5
6
7
# File 'lib/pump/encoder.rb', line 5

def base
  @base
end

#encoder_configObject (readonly)

Returns the value of attribute encoder_config.



5
6
7
# File 'lib/pump/encoder.rb', line 5

def encoder_config
  @encoder_config
end

#encoder_optionsObject (readonly)

Returns the value of attribute encoder_options.



5
6
7
# File 'lib/pump/encoder.rb', line 5

def encoder_options
  @encoder_options
end

#root_nameObject (readonly)

Returns the value of attribute root_name.



5
6
7
# File 'lib/pump/encoder.rb', line 5

def root_name
  @root_name
end

Instance Method Details

#encode(object, options = {}) ⇒ String

Encode a object or an array of objects to an XML-string.



54
55
56
57
# File 'lib/pump/encoder.rb', line 54

def encode(object, options={})
  object = object.to_a if defined?(ActiveRecord::Relation) && object.is_a?(ActiveRecord::Relation)
  object.is_a?(Array) ? encode_array(object, options) : encode_single(object, options)
end