ODM

Simple Object Data Mapper

Parse Array of Hash or any complex object into subclass of the main ones to make it more object oriented on the fly :) Why? Because you can make scopes like that to incoming datas like json. And with that you can have random methods on the objects without the need of analyze the data :)

at this point the following classes (and they child's) are implemented:

  • [ Module, Array, Hash, Regexp, String, File, IO ]

initialize method will be called directly in array and hash classes, but will be exception handled if Argument or NoMethod Error occurs

Example

Simple

we can simply pass to opts the defaults we want to be used when the parser find an object


    require 'odm'

    #> some random class as target models

    class STRING < String
    end

    class ARRAY < Array
    end

    class HASH < Hash
    end

    odm= ODM.new do |opts|
      opts.array  = ARRAY
      opts.hash   = HASH
      opts.string = STRING
    end

    var= odm.parse [ {hello: {"world" => "hey!"} }, 123 ]
    puts var.inspect,var.class,var[0].class,var[0][:hello].keys[0].class
    #> [{:hello=>{"world"=>"hey!"}}, 123], ARRAY, HASH, STRING

Complex



    class ARRAYDEF < Array
    end

    class ARRAY1 < Array
    end

    class ARRAY2 < Array
    end

    odm= ODM.new(

        # defaults for deepness level 0
        { array: ARRAY1 },

        # defaults for deepness level 1
        { array: ARRAY2 },

        # default instance variables to be set for each object
        [:var,"hello"]      ) do |opts|

      # defaults for else places (if no target class given,than no parse will be made)
      opts.array= ARRAYDEF

    end

    #> test obj
    obj= [[[]]]

    var= odm.parse obj

    #> make an ARRAY1[ ARRAY2[ ARRAYDEF[] ] ]
    #> each object got a var instance variable with a "hello" string

Better to be known

when parsing a Hash or an Array object, the default initialize method is [] and not :new when parsing else objects the default behavior is trying to call the class :new method with the original object

YAML and JSON

yaml and json can be parsed too:

  • parse_json
  • parse_yaml
    • or parse_yml
  • parse_safe_yaml
    • or parse_safe_yml

Example for yaml parse


    require 'yaml'
    yaml_data= [ {hello: {"world" => "hey!"} }, 123 ].to_yaml

    puts odm.parse_yml(yaml_data).inspect
    #> [{:hello=>{"world"=>"hey!"}}, 123]