ODM

Simple Object Data Mapper

Parse Array of Hash into random Class of classes to make it more object oriented on the fly :)

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

    #>              for deepness level 0  |  for deepness level 1     set instance variable "var" with value: "hello"
    odm= ODM.new(    { array: ARRAY1 },      { array: ARRAY2 },      [:var,"hello"]   ) do |opts|

      # defaults for else places (if block not given, 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]