Module: LAA::FeeCalculator::HasManyable::ClassMethods

Defined in:
lib/laa/fee_calculator/has_manyable.rb

Defined Under Namespace

Modules: Searchable

Instance Method Summary collapse

Instance Method Details

#has_many(association) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/laa/fee_calculator/has_manyable.rb', line 19

def has_many(association)
  define_method("#{association}_uri".to_sym) do |scheme_pk = nil, id = nil|
    uri = scheme_pk.nil? ? "#{association.to_s.tr('_', '-')}/" : "fee-schemes/#{scheme_pk}/#{association.to_s.tr('_', '-')}/"
    uri = uri.concat(id.to_s, '/') unless id.nil?
    Addressable::URI.parse(uri)
  end

  define_method(association) do |id = nil, **options|
    id ||= options&.fetch(:id, nil)
    uri = self.send("#{association}_uri", self.id, id)
    uri.query_values = options.reject { |k, _v| k.eql?(:id) }

    json = get(uri).body

    ostruct = JSON.parse(json, object_class: OpenStruct)
    return ostruct unless ostruct.respond_to?(:results)

    ostruct.results.extend Searchable
  end
end