Sha256: 723b24abf6b823f446aa0d02c420ec9bd8485eafcec941f2a7f581556c311b65

Contents?: true

Size: 1.63 KB

Versions: 25

Compression:

Stored size: 1.63 KB

Contents

class MLS::Parser
  
  attr_reader :object
  
  def initialize(object=nil, persisted=true)
    @object = object || self.class.object_class.new({}, persisted)
  end
  
  def parse(data)
    attributes = extract_attributes(data)[self.class.root_element]
    update_attributes(attributes)
    object
  end
  
  def build(attributes)
    update_attributes(attributes)
    object
  end
  
  def update_attributes(attributes)
    attributes.each {|k,v| self.send("#{k}=".to_sym, v) } if attributes
  end
  
  def self.parse(data)
    self.new.parse(data)
  end

  # TODO: TEST ME
  def self.build_collection(hash, options={})
    root = options[:collection_root_element] || collection_root_element
    collection = []
    hash[root].each do |attrs|
      collection << build(attrs)
    end
    collection
  end
  
  def self.parse_collection(data, options={})
    build_collection(extract_attributes(data), options)
  end
  
  def self.build(attributes)
    self.new.build(attributes)
  end
  
  def self.update(object, data)
    self.new(object).parse(data)    
  end
  
  def method_missing(method, *args, &block)
    object.__send__(method, *args, &block) if object.methods.include?(method)
  end  
  
  def extract_attributes(data)
    Yajl::Parser.new(:symbolize_keys => true).parse(data)
  end
  def self.extract_attributes(data)
    Yajl::Parser.new(:symbolize_keys => true).parse(data)
  end

  def self.object_class
    @object_class ||= ActiveSupport::Inflector.constantize(self.to_s.sub('::Parser',''))
  end
  
  def self.root_element
    object_class.root_element
  end
  
  def self.collection_root_element
    object_class.collection_root_element
  end
  
end

Version data entries

25 entries across 25 versions & 1 rubygems

Version Path
mls-0.5.5 lib/mls/parser.rb
mls-0.5.4 lib/mls/parser.rb
mls-0.5.3 lib/mls/parser.rb
mls-0.5.2 lib/mls/parser.rb
mls-0.5.1 lib/mls/parser.rb
mls-0.5.0 lib/mls/parser.rb
mls-0.4.0 lib/mls/parser.rb
mls-0.3.8 lib/mls/parser.rb
mls-0.3.7 lib/mls/parser.rb
mls-0.3.6 lib/mls/parser.rb
mls-0.3.5 lib/mls/parser.rb
mls-0.3.4 lib/mls/parser.rb
mls-0.3.3 lib/mls/parser.rb
mls-0.3.2 lib/mls/parser.rb
mls-0.3.1 lib/mls/parser.rb
mls-0.3.0 lib/mls/parser.rb
mls-0.2.54 lib/mls/parser.rb
mls-0.2.53 lib/mls/parser.rb
mls-0.2.52 lib/mls/parser.rb
mls-0.2.51 lib/mls/parser.rb