Module: AppQuery::Mappable

Extended by:
ActiveSupport::Concern
Defined in:
lib/app_query/mappable.rb

Overview

Note:

This is a BaseQuery middleware. Include it in classes that inherit from BaseQuery to transform hash results into typed objects.

Middleware concern that maps query results to Ruby objects in BaseQuery subclasses.

Include this module to automatically convert result hashes into typed objects like +Data+ classes or +Struct+s.

By default, looks for an +Item+ constant in the query class. Use +map_to+ to specify a different class.

Examples:

With default Item class

class ArticlesQuery < ApplicationQuery
  include AppQuery::Mappable

  class Item < Data.define(:title, :url, :published_on)
  end
end

articles = ArticlesQuery.new.entries
articles.first.title  # => "Hello World"

With explicit map_to

class ArticlesQuery < ApplicationQuery
  include AppQuery::Mappable
  map_to :article

  class Article < Data.define(:title, :url)
  end
end

Skip mapping with raw

articles = ArticlesQuery.new.raw.entries
articles.first  # => {"title" => "Hello", "url" => "..."}

Combining with Paginatable

class ArticlesQuery < ApplicationQuery
  include AppQuery::Paginatable
  include AppQuery::Mappable

  class Item < Data.define(:title, :url)
  end
end

# Results are paginated AND mapped to Item objects
ArticlesQuery.new.paginate(page: 1).entries.first.title

See Also:

Instance Method Summary collapse

Instance Method Details

#rawObject



64
65
66
67
# File 'lib/app_query/mappable.rb', line 64

def raw
  @raw = true
  self
end

#select_allObject



69
70
71
# File 'lib/app_query/mappable.rb', line 69

def select_all
  map_result(super)
end

#select_oneObject



73
74
75
# File 'lib/app_query/mappable.rb', line 73

def select_one
  map_one(super)
end