Module: Httpsql::ClassMethods

Defined in:
lib/httpsql.rb

Instance Method Summary collapse

Instance Method Details

#grape_documentation(ctx = nil) ⇒ Hash

Provide documentation for Grape end points

Examples:

Including documentation

params do
  MyModel.grape_documentation(self)
end

Parameters:

  • ctx (Object) (defaults to: nil)

    The calling object

Returns:

  • (Hash)


61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/httpsql.rb', line 61

def grape_documentation(ctx=nil)
  columns.each do |c|
    opt_hash = {}
    if (k = httpsql_sql_type_conversion(c.type))
      opt_hash[:desc] = k.to_s
    end
    ctx.optional c.name, opt_hash
  end
  ctx.optional :field, desc: "An array of strings: fields to select from the database"
  ctx.optional :group, desc: "An array of strings: fields to group by"
  ctx.optional :order, desc: "An array of strings: fields to order by"
  ctx.optional :join,  desc: "An array of strings: tables to join (#{httpsql_join_tables.join(',')})"
end

#with_params(params = {}) ⇒ ActiveRecord::Relation

The method to call within API end points

Examples:

Constraining a model index end point

resource :my_models
  get '/' do
    MyModel.with_params(params)
  end
end

Parameters:

  • params (Hash) (defaults to: {})

    The params hash for a given API request

Returns:

  • (ActiveRecord::Relation)

Raises:

  • (ActiveRecord::StatementInvalid)

    if any fields or functions are invalid

  • (ActiveRecord::ConfigurationError)

    if a join relation is invalid



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/httpsql.rb', line 20

def with_params(params={})
  @httpsql_params = params
  @httpsql_conds  = []

  @httpsql_fields = httpsql_extract_fields
  joins  = httpsql_extract_joins
  groups = httpsql_extract_groups
  orders = httpsql_extract_orders

  httpsql_valid_params.each do |k,v|
    k, m = k.to_s.split('.')
    next if k.to_s == 'access_token' 

    # column.sum, column.function=arg1, column.predicate=x
    if m
      httpsql_extract_method(k, m, v)

    # column[]=1&column[]=2 or column=x
    else
      httpsql_extract_default_predicates(k, v)
    end

  end

  @httpsql_conds = @httpsql_conds.inject{|x,y| x.and(y)}

  ar_rel = where(@httpsql_conds)
  ar_rel = ar_rel.select(@httpsql_fields) if @httpsql_fields.any?
  ar_rel = ar_rel.joins(joins)  if joins.any?
  ar_rel = ar_rel.group(groups) if groups.any?
  ar_rel = ar_rel.order(orders) if orders.any?
  ar_rel
end