Skip to content
Alex edited this page Jul 29, 2018 · 2 revisions

Result parsing

If db gem doesn't parse result as you wish you can specify :types option to the sending_request params. In future there should be possibility to define them in constructor.

# send_request without :types option
result.array_field = "{'value_1', 'value_2'}"
# send_request with types: { array_field: :array }
result.array_field = ['value_1', 'value_2']

# types can be nested {heavy_field: [:array, :hstore]}
result.heavy_field => [{name: 'mrgl'}, {name: 'Aeonax'}]

Result implementation

::Result

From send_request you will get Terrazine::Result instance. You can access from it:

  • rows - Array of Terrazine::Row instances
  • fields - response fields from db
  • field_name - field value from first row
  • options - passed in send_request options. Methods each, each_with_index, first, last, map, count, present? delegating to the rows. Method index delegating to the fields.
result.rows          # => [<Row..>, <Row..>]
result.fields        # => ['name', 'role']
result.name          # => 'mrgl'
result.map(&:name)   # => ['mrgl', 'Aeonax']

::Row

You can access from it:

  • values - Array of row values
  • field_name - field value
  • pg_result - parent ::Result instance. Will be renamed to result_instance-_- Method index delegating to pg_result.fields.
row = result.rows[2]
row.values                 # ['Aeonax', 'khakiit']
row.role                   # 'khajiit'
row.pg_result == result    # true
row.index(:role)           # 2

Result representation

Result have method present that will return Hash or Array with Hashes. It accept optional options, that will be merged with result.options[:presenter_options].

Presenter Options

  • :array - will wrap response hash in Array in case of result.row.count < 2. if result.row.count.zero? returns empty array.
  • :structure - Hash with field as key and value as modifier. Modifier will rewrite field value in result. Modifier acts:
    • Proc - it will call proc with row as argument, and! then pass it to presenter again... Why?-_-
    • another Result instance - it will call result.present
    • anything else will be returned without changes
  • :delete - !will be soon! - Symbol or Array with Symbols that should be deleted from hash result.
# present without present options
result.present        # => [{name: 'mrgl', role: 'murlock'}, {name: 'Aeonax', role: 'khajiit'}]
# with presenter_options
result.present(structure: { speach: ->(row) { row.role == 'murlock' ? 'Mrrrgl!!' : 'This finished conversation' } })
# => [{name: 'mrgl', role: 'murlock', speach: 'Mrrrrgl!'}, 
#     {name: 'Aeonax', role: 'khajiit', spaech: 'This finished conversation'}]