Skip to content

Instantly share code, notes, and snippets.

@bolshakov
Last active August 29, 2015 14:21
Show Gist options
  • Save bolshakov/53846d9a6e31f973ef7c to your computer and use it in GitHub Desktop.
Save bolshakov/53846d9a6e31f973ef7c to your computer and use it in GitHub Desktop.
Trailblazer use case: listing items

I've tried to user Trailblazer to fetch some data and render it as json. Here described several problems:

  • It is imposible to validate just params, without model.
  • Operation#validate returns instance of operation, not value of the block. So I should use intermediate variable to return value from #process method.

Compare:

# returns `Operation`
def process(params)
  validate(params, model) do |f|
    model
  end
end
# returns model
def process(params)
  model
end

This behaviour is very confusing.

  • If I return data from #process method could not access operation' errors from else block in controller
  • In the code base result of running Operation#run always refered as operation, but it is not Operation, it is whatever returns #process
module Pagination
extend ActiveSupport::Concern
included do
contract do
property :limit, validates: { numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 50 } }
property :offset, validates: { numericality: { greater_than_or_equal_to: 0 } }
end
end
end
class User < ActiveRecord::Base
class Purchases < Trailblazer::Operation
include Pagination
contract do
property :ids, type: List
end
def process(params)
validate(params) do |f|
purchases =
if f.ids
f.user.purchases.where(id: f.ids)
else
f.user.purchases
end
purchases.paginate(params.slice(:limit, :offset))
end
end
end
end
class PurchasesController < ActionController::Base
def index
run User::Purchases params.merge(user: current_user) do |purchases|
render json: purchases
end.else do |operation|
fail BadRequestError, operation.errors.full_messages
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment